0
我嘗試自定義AuthorizeAttribute以在寧靜服務中進行身份驗證。我想將信息寫入日誌文件。但它沒有奏效。我在日誌路徑中看不到任何日誌文件。 (我已啓用IIS_USER權限)asp.net中的AuthorizeAttribute MVC無法將日誌寫入文件
另外,我甚至發現如果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";
}
}
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();
}
謝謝!我發現我混淆了System.Web.http.AuthorizeAttribute和System.Web.Mvc.AuthorizeAttribute!現在它適用於我改變System.Web.http.AuthorizeAttribute! – Jeff