【问题标题】:Custom error page when using Owin使用 Owin 时的自定义错误页面
【发布时间】:2015-06-22 16:52:55
【问题描述】:

我正在使用 Owin 来托管 WebAPI 控制器。我有 Owin 中间件,它执行身份验证并在身份验证失败时设置以下内容:

context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;

发生这种情况时,我想向用户显示一个带有一些说明的 HTML 页面。 (例如,“您需要登录。”)

目前我只是将用户重定向到 accessdenied.html 页面,但我希望直接显示拒绝访问而不重定向用户(我不希望 Web 浏览器中的 Location 字段改变)。

我假设我可以即时生成 HTML 并将其添加到响应中,例如通过从资源中读取 HTML 内容。

我的问题是:是否可以使用配置自动显示自定义访问被拒绝错误页面?在“传统”ASP.NET 中,可以在 web.config 中设置 customErrors,但这似乎不适用于 Owin selfhost:

<customErrors>
  <error statusCode="401" redirect="~/accessdenied.html"/>
</customErrors>

【问题讨论】:

    标签: c# authentication asp.net-web-api owin custom-error-pages


    【解决方案1】:

    在我之前的项目中,我不得不使用这样的 Owin 中间件:

           app.Use((owinContext, next) =>
            {          
                return next().ContinueWith(x =>
                {
                    if (owinContext.Response.StatusCode == 500 /*or 401 , etc*/)
                    {                        
                        //owinContext.Response.Redirect(VirtualPathUtility.ToAbsolute("~/Home/Error"));
                        //this should work for self-host as well
                        owinContext.Response.Redirect(owinContext.Request.Uri.AbsoluteUri.Replace(request.Uri.PathAndQuery, request.PathBase + "/Home/Error"));
                    }
                });                
            });
    

    您必须先注册中间件。

    在这种情况下,我将用户重定向到错误视图,但作为一般做法,我会说最好有一个 HTML 静态页面。

    其实我认为有一个处理全局异常的扩展请求。 Have a look at this link...

    【讨论】:

    • 这不适用于自托管,因为VirtualPathUtilitySystem.Web 的一部分,需要IIS 才能正常工作。
    • 你应该改用这个:request.Uri.AbsoluteUri.Replace(request.Uri.PathAndQuery, request.PathBase + "/Home/Error")
    • 如果你做 Response.Redirect,它会将 HTTP 状态码更改为 302。
    • owin context 为您提供重定向选项。
    【解决方案2】:

    我遇到了同样的问题。我尝试设置 StatusCode 然后重定向到 401 页面。但是 Redirect 会将 StatusCode 更改为 302。

    我想出了读取 401.html 并将其写入响应的解决方案。它对我有用。

    context.Response.StatusCode = 401;
    var path = HttpContext.Current.Server.MapPath("/401.html");
    var html = System.IO.File.ReadAllText(path, Encoding.UTF8);
    context.Response.Write(html);
    

    【讨论】:

    • owin context 为您提供重定向选项。
    【解决方案3】:

    owin 为您提供重定向到错误页面的选项

    context.Response.Redirect(errUrl); //context就是owinContext

    您不需要任何特殊的 RedirectResult 或 RedirectToAction 方法。

    【讨论】:

    • 这样做的问题是,一旦您调用了“下一个”中间件,您只会收到 404 错误代码。向用户发送错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    相关资源
    最近更新 更多