如何MVC返回未经授权code,而不重定向到登录视图 [英] how can mvc return Unauthorized code without redirecting to LogIn view
问题描述
我的MVC Web应用程序提供用户两种类型。
My MVC web application serves two types of users.
- 首先一个比标准的Web浏览器;
- 第二个通过REST只返回JSON数据。
此外,
- 这都需要身份验证和授权;
- 这两种情况是有区别的基于路线,让我知道什么服务内容。
当用户访问应用程序,如果他们还没有登录,应用程序应该做出不同的反应。
When users access the application, if they are not logged in, the application should react differently.
- 在第一种情况下它应该返回默认的登录页面(这是罚款)。
- 在第二种情况下它应该只返回一个401未授权code。
我已经习惯了与WCF REST服务的工作,我可能引发这样的异常:
I'm used to working with WCF REST service where I could raise an exception like this:
throw new WebProtocolException(System.Net.HttpStatusCode.Unauthorized, exc.Message, exc);
和收到一个401消息。与内MVC同样的方法的问题,当我把状态code
是这样的:
and receive a 401 message. The problem with the same approach within MVC when I put the statusCode
like this:
HttpContext.Response.StatusCode = (Int32)HttpStatusCode.Unauthorized
它总是重定向到登录页面。
it always redirects to the LogIn page.
我怎样才能做到这一点?
How can I do this?
我试着尽快覆盖 AuthorizeAttribute
和处理 OnAuthorization
的功能,但还是因为我设置状态code
401它被重定向到登录页面。
I've tried overriding the AuthorizeAttribute
and handling the OnAuthorization
function, but still as soon as I set the statusCode
to 401 it gets redirected to the LogIn page.
推荐答案
要prevent登录页面重定向必须设置燮pressFormsAuthenticationRedirect
的属性 HttpContext.Response
为true;
To prevent login page redirection you must set SuppressFormsAuthenticationRedirect
property of HttpContext.Response
to true;
HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
这篇关于如何MVC返回未经授权code,而不重定向到登录视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!