Friday, 30 August 2013

AuthorizeAttribute at asp.net MVC cannot write log to file

AuthorizeAttribute at asp.net MVC cannot write log to file

I try to customize AuthorizeAttribute for authentication at restful
service. I want to write information into a log file. But it didn't work.
I don't see any log file at my log path. (I have enable permission to
IIS_USER)
Also, I even found that if AuthorizeCore return false, my test client can
still get the result. Is somewhere in my code wrong? Or something I
misunderstand how AuthorizeAttribute work?
PS. I also found that if I switch log part to ApiController it will work!
It's so weird!
Filter
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
using (StreamWriter sw = new
StreamWriter(@"C:\inetpub\wwwroot\mvctest\logs\Trace.log", true,
Encoding.UTF8))
{
IEnumerable<String> header =
httpContext.Request.Headers.GetValues("User");
foreach (String str in header)
{
sw.WriteLine(str);
}
sw.Flush();
}
return base.AuthorizeCore(httpContext);
}
}
ApiController
public class ValuesController : ApiController
{
// GET api/values
[MyAuthorizeAttribute]
public List<String> Get()
{
return new List<String> { "Success", "Get" };
}
// GET api/values/5
[MyAuthorizeAttribute]
public String Get(int id)
{
return "Success";
}
}
TestClient
static void Main(string[] args)
{
try
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://localhost/mvctest/api/values/5");
request.Headers.Add("User", "Darkurvivor");
using (WebResponse response = request.GetResponse())
using (StreamReader sr = new
StreamReader(response.GetResponseStream()))
{
String data = sr.ReadToEnd();
Console.WriteLine(data);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}

No comments:

Post a Comment