Asp.Net MVC如何返回401响应码
需求:
在默认创建的Asp.Net MVC项目中(这里使用VS2013),需要手动返回一个401响应码给浏览器。我们的代码可能是下面这样子的。
-
1 public ActionResult UnauthorizedAccess() 2 { 3 return new HttpStatusCodeResult((int)HttpStatusCode.Unauthorized); 4 }
-
1 // 使应用程序可以使用 Cookie 来存储已登录用户的信息 2 // 并使用 Cookie 来临时存储有关使用第三方登录提供程序登录的用户的信息 3 // 配置登录 Cookie 4 app.UseCookieAuthentication(new CookieAuthenticationOptions 5 { 6 AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 7 LoginPath = new PathString("/Account/Login"), 8 Provider = new CookieAuthenticationProvider 9 { 10 // 当用户登录时使应用程序可以验证安全戳。 11 // 这是一项安全功能,当你更改密码或者向帐户添加外部登录名时,将使用此功能。 12 OnValidateIdentity = SecurityStampValidator.OnValidateIdentity
( 13 validateInterval: TimeSpan.FromMinutes(30), 14 regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 15 } 16 });
-
1 public void Application_PreSendRequestHeaders(object sender, EventArgs e) 2 { 3 //处理401响应被多个框架重写的问题 4 var values = Response.Headers.GetValues(ForceHttpStatusCodeResult.ForceHttpUnauthorizedHeaderName); 5 if (values != null && values.Contains(ForceHttpStatusCodeResult.ForceHttpUnauthorizedHeaderValue)) 6 { 7 Response.ClearHeaders(); 8 Response.StatusCode = (int)HttpStatusCode.Unauthorized; 9 } 10 }
1 ///此时我们在Action中就可以返回我们需要的任意响应码了2 /// 强制返回指定的响应码 3 /// 401响应码会被MVC框架和OWIN授权认证的中间件给重写 4 /// 5 public class ForceHttpStatusCodeResult : HttpStatusCodeResult 6 { 7 8 public const string ForceHttpUnauthorizedHeaderName = "ForceHttpUnauthorizedHeader"; 9 public const string ForceHttpUnauthorizedHeaderValue = "true"; 10 11 public ForceHttpStatusCodeResult(int state) 12 : this(state, "") 13 { } 14 15 public ForceHttpStatusCodeResult(int state, string statusDescription) 16 : base(state, statusDescription) 17 { 18 if (state == (int)HttpStatusCode.Unauthorized) 19 { 20 SetForceHttpUnauthorizedHeader(); 21 } 22 } 23 24 25 private void SetForceHttpUnauthorizedHeader() 26 { 27 System.Web.HttpContext.Current.Response.AddHeader(ForceHttpUnauthorizedHeaderName, ForceHttpUnauthorizedHeaderValue); 28 } 29 }
-
1 public ActionResult UnauthorizedAccess() 2 { 3 return new ForceHttpStatusCodeResult((int)HttpStatusCode.Unauthorized); 4 }