直接向客户端抛出HTTPResponseException

问题描述:

我有一个API实现在一个MVC(Asp.net 4.5.2)的ApiController下。在那个api中,我想用HttpResponseMessage(HttpStatusCode.Unauthorized)抛出一个HttpResponseException并指定一个ReasonPhrase。如何直接发送给客户端,而不是让asp/mvc尝试将它们重定向到登录页面?直接向客户端抛出HTTPResponseException

Asp.Net窗体身份验证模块转换如果使用UseCookieAuthentication 401至302

,然后通过改变OnApplyRedirect抑制这种

文件Startup.Auth.cs - > ConfigureAuth方法- >内部app.UseCookieAuthentication(新CookieAuthenticationOptions {提供商=新CookieAuthenticationProvider {- >添加OnApplyRedirect

 app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      Provider = new CookieAuthenticationProvider 
      { 
       OnApplyRedirect = context => 
       { 
        if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api"))) 
        { 
         context.Response.Redirect(context.RedirectUri); 
        } 
       } 
      } 
     }); 
+0

我不认为我完全理解你的指示。我已经将这个片段添加到了ConfigureAuth(app)之下的Startup.Configuration(IAppBuilder应用程序);但是我仍然被重定向到登录。 – Roger

+0

不在startup.configuration下面。请去文件startup.auth.cs。搜索线app.UseCookieAuthentication。在UseCookieAuthentication里面,当你设置提供者时,复制粘贴这段代码(重写OnApplyRedirect) – Kaushal

+0

啊,是的。谢谢,这正是我所需要的。 API现在可以使用auth或api错误返回详细的解释,并且应用程序的其余部分的身份验证不变。 – Roger

var message = new HttpResponseMessage(HttpStatusCode.Unauthorized); 
message.ReasonPhrase = "Hello"; 
throw new HttpResponseException(message); 

但重定向取决于Web.config设置。我觉得你有一个像这样在web.config中somethink鉴定部分:

<system.web> 
    <authentication mode="Forms"> 
    <forms loginUrl="/Login/Index"></forms> 
    </authentication> 
    </system.web> 

如果删除这部分,重定向不会发生。但在这种情况下,您应该自行实施身份验证。

+0

是的,那正是我正在做的。但不是客户端收到错误消息,他们会跳到一个登录页面。我希望客户端调用API来获取错误。 – Roger

+0

重定向发生在服务器端还是客户端? –

+0

据我所知,mvc看到未经授权的状态码并将请求路由到登录页面。我只是想让它返回一个错误。 – Roger