[英]Services.Configuration.Replace in .Net Core 2.2 Startup
我正在寻找替代默认API 404的选项,但未在Web API中找到路由错误,并且发现此链接覆盖路由
根据描述,我可以创建如下的类
public class HttpNotFoundAwareController:ApiControllerActionSelector
{
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
HttpActionDescriptor descriptor = null;
try
{
descriptor= base.SelectAction(controllerContext);
}
catch(HttpResponseException ex)
{
var code = ex.Response.StatusCode;
}
return descriptor;
}
}
但是,此替代也需要注册。 通过链接,应在WebAPIConfig中完成,如下所示
configuration.Services.Replace(typeof(IHttpControllerSelector), new HttpNotFoundAwareDefaultHttpControllerSelector(configuration));
但是我不确定,如何在.Net Core Startup.cs文件中注册覆盖? 因为没有“服务”可用的“替换”属性。
有人可以帮忙吗?
为了捕获404
并返回自定义错误,您可以尝试使用UseStatusCodePages
app.UseStatusCodePages(new StatusCodePagesOptions {
HandleAsync = async context =>
{
if (context.HttpContext.Response.StatusCode == StatusCodes.Status404NotFound)
{
await context.HttpContext.Response.WriteAsync($"{context.HttpContext.Request.Path} is not Found");
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.