HTTPS的404错误处理?

时间:2016-10-20 07:11:28

标签: c# asp.net-core http-status-code-404 asp.net-core-mvc

我是ASP.NET Core的新手并且正在尝试构建我的第一个网站。我正在努力处理错误,真的需要一些建议。

要处理404错误我正在使用代码         startup.cs中的app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");

使用家庭控制器

    [HttpGet("Home/error/{errcode}")]
    public IActionResult Error(int errCode)
    {         
        return View("Error", errCode);            
    }  

这似乎成功捕获404,500错误并显示错误视图页面,其中包含正确的代码。错误视图位于/Views/Shared/Error.cshtml

但是当我在startup.cs

中添加从HTTP到HTTPS的重定向时
        app.Use(async (context, next) =>
        {
            if (context.Request.IsHttps)
            {
                await next();
            }
            else
            {
                var httpsUrl = "https://" + context.Request.Host + context.Request.Path;
                context.Response.Redirect(httpsUrl);
            }
        });

错误处理将不再有效,并在Firefox中显示Secure Connection Failed Error code: SSL_ERROR_RX_RECORD_TOO_LONG

现在看起来像这样。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
          if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error/{0}");
            // StatusCodePagesMiddleware to handle errors     
            app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
        }
        app.UseStaticFiles();
        app.UseIdentity();

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

        app.Use(async (context, next) =>
        {
            if (context.Request.IsHttps)
            {
                await next();
            }
            else
            {
                var httpsUrl = "https://" + context.Request.Host + context.Request.Path;
                context.Response.Redirect(httpsUrl);
            }
        });
     }

如何在ASP.NET MVC Core1.0中使用HTTPS处理错误?

提前非常感谢你!

1 个答案:

答案 0 :(得分:0)

如果中间件很重要,请订购。您应首先进行重定向,然后使用MVC:

app.Use(async (context, next) =>
{
    // redirect
    ...
});

app.UseMvc(routes =>
{
    ...
}