.Net Core 2.x重定向到错误页面

时间:2018-05-14 18:06:24

标签: asp.net-core asp.net-core-mvc asp.net-core-2.0 asp.net-core-mvc-2.0 custom-error-handling

我有一个简单的ASP.Net Core 2.0 Web应用程序,我通过启用Windows身份验证和禁用匿名身份验证在项目属性中启用了Windows身份验证。

对于AD安全组在应用程序/站点级别过滤的授权,我在Startup.cs中有以下代码:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddAuthentication(IISDefaults.AuthenticationScheme);

        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                                .RequireAuthenticatedUser()
                                .RequireRole("Application - Administrator")
                                .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseAuthentication();

        //app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
        //app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");

        app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");



        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

要在未授权用户尝试访问应用程序时处理Http 403状态代码,它将重定向到自定义错误页面。所以我在Startup.cs中的Configure方法中尝试了以下3种方法:

app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

在HomeController中,我尝试了两种默认的Error方法

public IActionResult Error()
{
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

并自定义一个来处理特定的状态代码:

public IActionResult Error(string errCode)
{
    if (errCode == "500" || errCode == "404" || errCode == "403")
    {
        return View($"~/Views/Error/{errCode}.cshtml");
    }

    return View("~/Views/Shared/Error.cshtml");
}

我在/ Views / Error /文件夹下有一个简单的错误页面403.cshtml。

但它们都不起作用,都显示此页面: enter image description here

我想知道我是否错过了或忘记实施以显示格式化的错误页面?

提前致谢。

3 个答案:

答案 0 :(得分:1)

问题在于Error方法,它错过了AllowAnonymous属性,允许在用户授权失败时匿名访问错误方法。 归功于@Calc

答案 1 :(得分:1)

我不是100%确定,但应该有2种Windows身份验证变体:

  1. 主机仅允许经过身份验证的用户

    • 启用Windows Authentication并停用Anonymous Users
    • [Authorize][AllowAnonymous]无效,因为未经身份验证的请求永远不会到达您的应用
    • 因此您不能/不需要设置全局过滤器。您可能必须在服务器上设置友好的错误页面?

      public class Startup
      {
          public IConfiguration Configuration { get; }
      
          public Startup(IConfiguration configuration)
          {
              Configuration = configuration;
          }
      
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddMvc();
          }
      
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
              else
              {
                  app.UseExceptionHandler("/home/error");
              }
      
              app.UseStaticFiles();
      
              app.UseMvcWithDefaultRoutes();
          }
      } 
      
  2. 主机允许匿名用户和经过身份验证的用户

    • 同时启用Windows AuthenticationAnonymous Users
    • [Authorize]需要在Startup.cs

      上进行额外设置
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddAuthentication(IISDefaults.AuthenticationScheme);
      
          services.AddMvc(config =>
          {
              var policy = new AuthorizationPolicyBuilder()
                 .RequireRole("Application - Administrator")
                 .Build();
      
              config.Filters.Add(new AuthorizeFilter(policy));
          });
      }
      
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
          ...
      
          app.UseStatusCodePagesWithReExecute("/error", "?code={0}");
      
          app.UseAuthentication();
      
          app.UseMvcWithDefaultRoutes();
      }
      
    • 您需要在错误控制器上使用[AllowAnonymous]来覆盖[Authorize]全局过滤器以允许匿名请求。

      [AllowAnonymous]
      public class ErrorController : Controller
      {
          public IActionResult Index(int? code)
          {
              ...
          }
      }
      

答案 2 :(得分:1)

在startup.configure(IApplicationBuilder应用程序,IHostingEnvironment env)中尝试app.UseStatusCodePagesWithRedirects("/Home/Error/{0}");

在ASP.NET CORE2.0 Web应用程序上工作

它将处理任何类型的HTTP错误