更新时间:2023-11-20 23:40:52
我刚才已经想通了,我可以在HandleUnauthorized正常请求和Ajax请求的过滤器
我在我的AuthorizeAttribute子类中重写请求方法。这样一个Ajax请求我可以创建一个JSON结果或为此事别的东西,和正常的请求仍然会显示在登录页面。在code是如下:
I have just figured it out, I can filter between normal requests and ajax requests in the HandleUnauthorized Request method that I override in my AuthorizeAttribute sub class. That way for an ajax request I can create a json result or something else for that matter, and for normal requests it would still show up the login page. the code is as follows:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
JsonResult UnauthorizedResult = new JsonResult();
UnauthorizedResult.Data = "{ request : 'unauthorized' }";
UnauthorizedResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
filterContext.Result = UnauthorizedResult;
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
我依然会不标记我的问题是解决了,所以如果有人可以建议做一个更好的方式,我仍然开放的建议。
still I will not mark my question as resolved, so if someone can suggest a better way of doing it, I am still open to suggestions.