繁体   English   中英

在 ASP.NET Core 2 中使用 UseExceptionHandler() 和 API 处理和 404 处理

[英]using UseExceptionHandler() with API handling and 404 handling in ASP.NET Core 2

我有以下情况:

  • ASP.NET 核心 2 服务于/api/*上的 api 请求
  • ASP.NET Core 2 在/health上服务健康请求
  • ASP.NET Core 2 在/svc/*上服务代理请求
  • ASP.NET Core 2 在/app/上提供 SPA(如果您将 go 指向example.com ,它将提供来自/app/文件夹的文件。

现在,如果有人请求一个不存在的实体,则会引发异常。 这是通过使用 Startup.cs 中的以下内容来处理的

app.UseExceptionHandler("/error");

ErrorController 处理这些异常并返回NotFound()BadRequest()等内容。最后,它们都是 JSON 响应。

现在,如果您从 go 到/hshfdhfgh url,这将导致一个空的 404 页面,因为没有匹配项。 但我想做的是能够为错误页面添加一些自定义 HTML 视图。 也许与 Razor 页面或其他东西。

我已经查过了,建议您使用UseExceptionHandler("/error")方法,这样您就可以返回一些视图。 但这会与我的 JSON 响应冲突!

我唯一能想到的是:

if request does not start with /health, /svc/, /, /app or /api/
    app.UseExceptionHandler("/error/404");
else
    app.UseExceptionHandler("/error");

但这感觉很hacky。 还有其他方法吗?

而且,向我的项目添加 razor 支持的最佳/最简单方法是什么? 目前它没有。

您可以以此为起点(它是 netcore 3.1,但我认为从 2 迁移时我们不必进行重大更改)。 It feels hacky and it's pain to get the handler itself right, and to put it at the exactly right place in Startup (especially if you combine it with things like dealing properly with Unauthorized responses, razor views and static files for those razor views). 但是我没有找到更好的方法。

public static readonly PathString ApiPath = new PathString("/api");
public static readonly PathString StaticFilePath = new PathString("/site");
static bool IsApiRequestPredicate(HttpContext context) => context.Request.Path.StartsWithSegments(ApiPath, StringComparison.InvariantCulture);
static bool IsStaticFilePredicate(HttpContext context) => context.Request.Path.StartsWithSegments(StaticFilePath, StringComparison.InvariantCulture);

...

app.UseWhen(x => !IsApiRequestPredicate(x) && !IsStaticFilePredicate(x), builder =>
{
    builder.UseStatusCodePagesWithReExecute("/Error/StatusCodeViewReexecuteHandler/{0}");
    app.UseDeveloperExceptionPage();
});
app.UseWhen(x => IsApiRequestPredicate(x), builder =>
{
    builder.UseExceptionHandler("/Error/ExceptionApiReexecuteHandler");
    builder.UseStatusCodePagesWithReExecute("/Error/StatusCodeApiReexecuteHandler/{0}");
});

您也可以仅使用一个处理程序并根据 ErrorController 操作中的 OriginalPath 进行决定:

var errorFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (errorFeature.OriginalPath.StartsWith("/api", StringComparison.InvariantCulture))
{
    return BadRequest(new { error = "entity not found" });
} else {
    return View("NotFound");
}
// exceptionFeature gives you access to the exception thrown

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM