代码之家  ›  专栏  ›  技术社区  ›  lonix

ASP中单独的状态代码页。NET核心Razor页面

  •  0
  • lonix  · 技术社区  · 2 年前

    我正在使用ASP。NET核心Razor页面与标识。我使用 StatusCodePages middleware 以标准方式:

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

    在那个剃刀页面中,我可以打开状态代码来呈现401、403、404和“其他”(范围为400..599的所有其他代码)的不同内容。然而,这会变得一团糟;我更喜欢分开几页。

    因此,与其这样:

    • /页面/错误.cshtml

    我想要这个:

    • /页码/401.chtml
    • /页码/403.chtml
    • /页码/404.chtml
    • /页码/400_599.cshtml

    这可能吗?

    我已经知道的丑陋的变通方法:

    • 我可以使用URL模板 "/Error/{0}" ,但这是不切实际的:我必须为400.599范围内的每个代码定义一个单独的页面。我绝对不能这么做。
    • 在“/Pages/Error.cs.html.cs”页面模型类中,我可以根据状态代码重定向到不同的页面。我宁愿不这样做,我怀疑这对SEO不好。
    • 对于“/Error”端点,我可以使用带有视图的MVC控制器(而不是Razor Pages);action方法可以返回适当的视图。这不是一个糟糕的解决方案,但增加了不必要的复杂性;我更喜欢Razor Pages的方法。
    1 回复  |  直到 2 年前
        1
  •  1
  •   Rena    2 年前

    我想要这个:

    /Pages/401.cshtml/Pages/403.cshtml/Pages/404.cshtml /Pages/400_599.cshtml有可能吗?

    当然可以,只需在中创建页面 Pages 文件夹如下: enter image description here

    然后使用 app.UseStatusCodePagesWithReExecute("/{0}") 在Program.cs中:

    app.UseStatusCodePagesWithReExecute("/{0}");
    app.UseExceptionHandler("/500");
    
    //app.UseDeveloperExceptionPage();
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapRazorPages();
    
    app.Run();
    

    对于包罗万象的页面 ,您可以获得如下错误页面:

    @page "/Error/{statusCode}"
    @model ErrorModel
    @{
        var statusCode = HttpContext.Request.RouteValues["statusCode"];
    
    }
    @switch (statusCode)
    {
        case "400":
            <h1>BadRequest</h1>
            <p>You send wrong model to this resource.</p>
            break;
        case "401":
            <h1>Unauthorized</h1>
            <p>You are not authorized to this resource.</p>
            break;
        case "403":
            <h1>Forbidden</h1>
            <p>You don't have permission to this resource.</p>
            break;
        case "404":
            <h1>Not Found</h1>
            <p>The resource you are looking for could not be found.</p>
            break;
        default:
            <h1>Error @(statusCode)</h1>
            <p>An error occurred while processing your request.</p>
            break;
    }
    

    程序.cs:

     app.UseStatusCodePagesWithReExecute("/Error/{0}");
     app.UseExceptionHandler("/Error/500");
    
    推荐文章