如何禁用AJAX/JSON请求的401响应代码(重定向到登录页面)的标准ASP.NET处理?
对于网页来说没关系,但对于AJAX,我需要获得正确的401错误代码而不是好看的302/200用于登录页面.
更新:来自ASP.NET MVC的PM的Phil Haack有几个解决方案 - http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot -want.aspx
在经典ASP.NET中,当使用Ajax调用WebMethod时,您将获得401 http响应代码.我希望他们能在未来的ASP.NET MVC版本中进行更改.现在我正在使用这个黑客:
protected void Application_EndRequest() { if (Context.Response.StatusCode == 302 && Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { Context.Response.Clear(); Context.Response.StatusCode = 401; } }
开发ASP.NET运行时,如果HttpResponse.StatusCode
设置为401,它总是会重定向用户,但只有在
找到Web.config 的部分时才会重定向.
删除身份验证部分将要求您实现重定向到属性中的登录页面,但这不应该是一个大问题.
我想要两种Forms身份验证,并为未经过身份验证的Ajax请求返回401.
最后,我创建了一个自定义AuthorizeAttribute并修饰了控制器方法.(这是.Net 4.5)
//web.config
//控制器
[Authorize(Roles = "Administrator,User"), Response302to401] [AcceptVerbs("Get")] public async TaskGetDocuments() { string requestUri = User.Identity.Name.ToLower() + "/document"; RequestKeyHttpClient , string> client = new RequestKeyHttpClient , string>(requestUri); var documents = await client.GetManyAsync >(); return Json(documents, JsonRequestBehavior.AllowGet); }
// authorizeAttribute
public class Response302to401 : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new JsonResult { Data = new { Message = "Your session has died a terrible and gruesome death" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.StatusDescription = "Humans and robots must authenticate"; filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true; } } //base.HandleUnauthorizedRequest(filterContext); } }