我尝试自定义 AuthorizeAttribute 以在 restful 服务中进行身份验证。我想将信息写入日志文件。但它没有用。我在我的日志路径中看不到任何日志文件。(我已启用 IIS_USER 权限)
另外,我什至发现如果 AuthorizeCore 返回 false,我的测试客户端仍然可以得到结果。我的代码中的某个地方有问题吗?还是我误解了 AuthorizeAttribute 的工作原理?
PS。我还发现,如果我将日志部分切换到 ApiController 它将起作用!太奇怪了!
筛选
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";
}
}
测试客户端
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();
}