且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC授权属性做了302重定向,当用户未授权

更新时间:2023-10-07 11:58:58

该授权属性的确实的返回一个HTTP 401未授权的响应。然而不幸的是,如果你启用了FormsAuthentication,401是由FormsAuthenticationModule,然后进行重定向到登录页面截获 - 然后返回一个HTTP 200(和登录页)回到您的Ajax请求

The Authorize attribute does return a Http 401 Unauthorized response. Unfortunately, however if you have FormsAuthentication enabled, the 401 is intercepted by the FormsAuthenticationModule which then performs a redirect to the login page - which then returns a Http 200 (and the login page) back to your ajax request.

***的办法是写自己的授权属性,然后如果你得到一个未经身份验证的要求,这也是一个Ajax请求,返回不同的HTTP状态code - 说403 - 这不是由formsAuthenticationModule抓住,你可以在你的Ajax方法来抓。

The best alternative is to write your own authorization attribute, and then if you get an unauthenticated request that is also an Ajax request, return a different Http status code - say 403 - which is not caught by the formsAuthenticationModule and you can catch in your Ajax method.