【问题标题】:Throw HTTPResponseException direct to client直接向客户端抛出 HTTPResponseException
【发布时间】:2017-07-01 04:20:31
【问题描述】:

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

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api


    【解决方案1】:
    var message = new HttpResponseMessage(HttpStatusCode.Unauthorized);
    message.ReasonPhrase = "Hello";
    throw new HttpResponseException(message);
    

    但重定向取决于 Web.config 设置。我认为您在 web.config 中有一些身份验证部分,如下所示:

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

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

    【讨论】:

    • 是的,这正是我正在做的。但是客户端没有收到错误消息,而是被退回到登录页面。我希望调用 api 的客户端得到错误。
    • 重定向发生在服务器端还是客户端?
    • 据我所知,mvc 看到 Unauthorized 状态代码并将请求路由到登录页面。我只是希望它返回一个错误。
    【解决方案2】:

    Asp.Net Form Authentication模块将401转换为302

    如果您使用 UseCookieAuthentication,则通过更改 OnApplyRedirect 来抑制它

    File Startup.Auth.cs --> ConfigureAuth 方法 --> 在 app.UseCookieAuthentication(new CookieAuthenticationOptions { Provider = new 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);
                        }
                    }
                }
            }); 
    

    【讨论】:

    • 我认为我没有完全理解您的指示。我已在 ConfigureAuth(app); 下面的 Startup.Configuration(IAppBuilder app) 中添加了 sn-p,但我仍然被重定向到登录。
    • 不低于 startup.configuration。请转到文件 startup.auth.cs。搜索行 app.UseCookieAuthentication。在 UseCookieAuthentication 内部,当您设置提供者时,复制粘贴此代码(以覆盖 OnApplyRedirect)
    • 啊,是的。谢谢,这正是我需要的。 API 现在可以返回带有 auth 或 api 错误的详细说明,并且应用程序其余部分的身份验证保持不变。
    • 另请注意,此代码将抑制虚拟路径 /api 的 302。您可能必须根据您的要求进行更改。如果您的 api 在虚拟路径中没有 /api,则使用逻辑来识别您的 api。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多