在MVC 4中,我们可以覆盖AuthorizeAttribute
类的一些方法来实现自定义Authorize属性。
例如:https://stackoverflow.com/a/21634723/6120338
public class DemoAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (Authorize(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
throw new HttpResponseException(challengeMessage);
}
private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try
{
var someCode = (from h in actionContext.Request.Headers where h.Key == "demo" select h.Value.First()).FirstOrDefault();
return someCode == "myCode";
}
catch (Exception)
{
return false;
}
}
}
和控制器将
[DemoAuthorize]
public class ValuesController : ApiController{
这是在MVC4中。但是如何在ASP.NET CORE中做同样的事情呢?
OnAuthorization
类中没有HandleUnauthorizedRequest
,Authorize
,AuthorizeAttribute
重写方法。