ASP .NET Core如何处理区域中的错误页面

时间:2019-06-26 11:51:31

标签: c# asp.net-core

if (env.IsDevelopment())
{ 
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Administration/Error");
    app.UseExceptionHandler("/Production/Error");
}

如何在剃刀页面的不同区域定义2个错误处理页面?

5 个答案:

答案 0 :(得分:3)

自定义异常处理程序页面的替代方法是为UseExceptionHandler提供lambda。使用lambda允许在返回响应之前访问发生错误的请求的路径。

以下是使用lambda进行异常处理的示例:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        var exceptionHandlerPathFeature =
            context.Features.Get<IExceptionHandlerPathFeature>();

        // Use exceptionHandlerPathFeature to process the exception (for example, 
        // logging), but do NOT expose sensitive error information directly to 
        // the client.

        if (exceptionHandlerPathFeature.Path.Contains("/Administration/"))
        {
            context.Response.Redirect("/Administration/Error");
        }

        if(exceptionHandlerPathFeature.Path.Contains("/Production/"))
        {
            context.Response.Redirect("/Production/Error");
        }
    });
});

您可以参考Handle errors in ASP.NET Core: Exception handler lambda

答案 1 :(得分:0)

我第一次摸索时更新了评论。 通过此link,您应该能够在调用中指定ExceptionHandler委托。我没有尝试过,但可能会解决您的问题。

 if (env.IsDevelopment())
 {          
      app.UseDeveloperExceptionPage();
 }
 else
 {
            ExceptionHandlerOptions options;
            options.ExceptionHandler = new RequestDelegate();
            app.UseExceptionHandler(options);
 }

您可能还希望将Areas作为一种可能的解决方案。它们使您可以定义应用程序中实现不同行为的子节。

答案 2 :(得分:0)

我不知道通过配置来实现此目标的任何方法。但是,您可以在错误处理程序中标识原始路径:

if (env.IsDevelopment())
{          
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

发生错误时,.NET将IExceptionHandlerPathFeature对象添加到Request对象。您可以使用它来获取路径:

public class HomeController : BaseController
{
    [Route("Error")]
    public IActionResult Error()
    {
        var exceptionPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

        var path = exceptionPathFeature.Path;

        if(path.Contains("/Administration/"))
            return View("AdministrationErrorPage");

        if(path.Contains("/Production/"))
            return View("ProductionErrorPage");

        return View("GenericErrorPage");
    }
}

答案 3 :(得分:0)

实现所需行为的另一种方法是使用UseWhen,如下所示:

<!--====== Contact ======-->
<section id="contact" class="contact section-padding">
    <div class="contact-overlay"></div>

    <!-- section header -->
    <div class="text-center mb-50">
        <h4 class="tit tit-center">GET IN TOUCH</h4>
    </div>

    <div class="contact-item container">
        <div class="row">

            <!-- contact form -->
            <div class="col-md-8 col-md-offset-2">
                <div class="form" id="contact-form" method="post" action="contact.php">
                    <div class="messages"></div>

                    <div class="controls">

                        <div class="col-sm-6">
                            <div class="form-group">
                                <input id="form_name" type="text" name="name" placeholder="Name *" required="required" data-error="Firstname is required.">
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>

                        <div class="col-sm-6">
                            <div class="form-group">
                                <input id="form_email" type="email" name="email" placeholder="Email *" required="required" data-error="Valid email is required.">
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>

                        <div class="col-sm-12">
                            <div class="form-group">
                                <input id="form_subject" type="text" name="subject" placeholder="Subject">
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>

                        <div class="col-sm-12">
                            <div class="form-group">
                                <textarea id="form_message" name="message" placeholder="Message *" rows="4" required="required" data-error="Message."></textarea>
                                <div class="help-block with-errors"></div>
                            </div>
                        </div>

                        <div class="col-sm-12">
                            <input type="submit" class="button" value="Send Message">
                        </div>
                        <div class="clear-fix"></div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</section>
<!--====== End Contact ======-->

答案 4 :(得分:0)

假设您将区域映射为路线值,请在 Configure 中添加以下内容:

app.UseStatusCodePages(context =>
{
    var area = context.HttpContext.Request.RouteValues["area"]?.ToString();
    var statusCode = context.HttpContext.Response.StatusCode;

    var location = (area, statusCode) switch {
        (string a, 404) => $"/{a}/page-not-found",
        (string a, int s) => $"/{a}/error/{s}",
        (null, 404) => "/page-not-found",
        (null, int s) => $"/error/{s}",
    };

    context.HttpContext.Response.Redirect(location);
    return Task.CompletedTask;
});