ASP.NET Core MVC – app.UseStatusCodePagesWithReExecute("/Error/{0}") always shows status code of 0 in controller

huangapple go评论68阅读模式
英文:

ASP.NET Core MVC - app.UseStatusCodePagesWithReExecute("/Error/{0}") always shows status code of 0 in controller

问题

以下是翻译的内容:

"我正在尝试为404和500错误实现一些自定义错误处理逻辑。我已经配置了我的错误控制器和一些简单的视图,现在我正在尝试使用中间件UseStatusCodePagesWithReExecute。我遇到的问题是,当我按照其他示例中的方式实现时,我的错误控制器路由中始终接收到一个状态代码为0。

为什么实际的HTTP状态代码没有作为参数值传递给控制器?

我的理解是,作为控制器方法中的int参数,我应该获得一个404状态代码,但它始终为0。我是否漏掉了什么?我尝试查看类似问题的其他示例,但似乎无法确定缺少什么。

以下是我正在使用的代码,使用ASP.NET Core 7 MVC + ASP.NET MVC 5。"

"Program.cs"

var builder = WebApplication.CreateBuilder(args);

// 将服务添加到容器中。
// MVC
if (builder.Environment.IsDevelopment())
    builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); // 用于调试视图
else
    builder.Services.AddControllersWithViews();

// 将服务添加到容器中。
// Blazor
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddHubOptions(options =>
    {
        options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
        options.EnableDetailedErrors = false;
        options.HandshakeTimeout = TimeSpan.FromSeconds(15);
        options.KeepAliveInterval = TimeSpan.FromSeconds(15);
        options.MaximumParallelInvocationsPerClient = 1;
        options.MaximumReceiveMessageSize = 32 * 1024;
        options.StreamBufferCapacity = 10;
    });

// Mudblazor UI库
// builder.Services.AddMudServices();

// 连接字符串配置
builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("ConnectionStrings"));

// EF 注册
builder.Services.AddDbContext<ArticlesContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ArticleDBconnectionString")));
builder.Services.AddDbContext<ProductContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ProductsConnection")));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

// 配置HTTP请求管道。
if (app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // 默认的HSTS值为30天。您可能需要为生产环境更改这个值,参见 https://aka.ms/aspnetcore-hsts。
    app.UseHsts();
}

// app.UseStatusCodePages();

app.UseStatusCodePagesWithReExecute("/Error/{0}");
app.UseMiddleware<ViewNotFoundExceptionMiddleware>();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

// Razor配置
app.MapRazorPages();
app.MapBlazorHub();

// MVC配置
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

"ErrorController.cs"

[AllowAnonymous]
public class ErrorController : Controller
{
    [Route("/Error/{code}")]
    new public ActionResult NotFound(int StatusCode)
    {            
        var errorFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        var error = errorFeature?.Error;
        ViewBag.ErrorMsg = "404 Page not found please try again XD";
        return View("Error", ViewBag);
    }

    [Route("/Error")]
    public ActionResult Error(int StatusCode)
    {
        var errorFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
        var error = errorFeature?.Error;
        ViewBag.ErrorMsg = "500 Server Error please try again XD";
        return View();
    }
}

请注意,我已将代码中的HTML标签、注释和代码格式留在原文中。

英文:

I am trying to implement some custom error handling logic for 404 and 500 errors. I have configured my error controller and some simple views for now, and i am trying to utilize the middleware UseStatusCodePagesWithReExecute. The issue I am facing is that when implementing it the way I see in other examples, I always receive a status code of 0 in my error controller route.

Why can is the actual http statuscode not being passed in as a parameter value to the controller?

My understanding is that I should be getting a status code of 404 as the int param in the controller method, but it is literally always 0. Am I missing something here? I have tried to look at other examples of similar issues here but cannot seem to determine what is missing.

Here is is code I am working with, using ASP.NET Core 7 MVC + ASP.NET MVC 5.

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// MVC
if (builder.Environment.IsDevelopment())
    builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); //for debugging views
else
    builder.Services.AddControllersWithViews();

// Add services to the container.
// Blazor
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor()
    .AddHubOptions(options =&gt;
    {
        options.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
        options.EnableDetailedErrors = false;
        options.HandshakeTimeout = TimeSpan.FromSeconds(15);
        options.KeepAliveInterval = TimeSpan.FromSeconds(15);
        options.MaximumParallelInvocationsPerClient = 1;
        options.MaximumReceiveMessageSize = 32 * 1024;
        options.StreamBufferCapacity = 10;
    });

//Mudblazor UI Lib
//builder.Services.AddMudServices();

//connstring configs
builder.Services.Configure&lt;AppSettings&gt;(
    builder.Configuration.GetSection(&quot;ConnectionStrings&quot;));

//EF registrations
builder.Services.AddDbContext&lt;ArticlesContext&gt;(options =&gt; options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;ArticleDBconnectionString&quot;)));
builder.Services.AddDbContext&lt;ProductContext&gt;(options =&gt; options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;ProductsConnection&quot;)));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Error&quot;);    
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();    
}

//app.UseStatusCodePages();

app.UseStatusCodePagesWithReExecute(&quot;/Error/{0}&quot;);
app.UseMiddleware&lt;ViewNotFoundExceptionMiddleware&gt;();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

//Razor config
app.MapRazorPages();
app.MapBlazorHub();

//mvc config
app.MapControllerRoute(
    name: &quot;default&quot;,
    pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);

app.Run();

ErrorController.cs

[AllowAnonymous]
    public class ErrorController : Controller
    {
        
        [Route(&quot;/Error/{code}&quot;)]
        new public ActionResult NotFound(int StatusCode)
        {            
            var errorFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();
            var error = errorFeature?.Error;
            ViewBag.ErrorMsg = &quot;404 Page not found please try again XD&quot;;
            return View(&quot;Error&quot;, ViewBag);
        }

        [Route(&quot;/Error&quot;)]
        public ActionResult Error(int StatusCode)
        {
            var errorFeature = HttpContext.Features.Get&lt;IExceptionHandlerFeature&gt;();
            var error = errorFeature?.Error;
            ViewBag.ErrorMsg = &quot;500 Server Error please try again XD&quot;;
            return View();
        }
    }

答案1

得分: 1

改用 statusCode 参数而不是 code 来更改路由。同时,应该使用驼峰命名法来命名变量,以遵循 C# 命名约定。

[Route(&quot;/Error/{statusCode}&quot;)]
public ActionResult NotFound(int statusCode)
英文:

Change the route with the statusCode parameter instead of code. While you should name the variable with camel case to follow the C# naming conventions.

[Route(&quot;/Error/{statusCode}&quot;)]
public ActionResult NotFound(int statusCode)

huangapple
  • 本文由 发表于 2023年4月1日 00:59:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定