[英]Services.Configuration.Replace in .Net Core 2.2 Startup
I am looking for option to override default 404 not found Route error in Web API and found this link Override Route 我正在寻找替代默认API 404的选项,但未在Web API中找到路由错误,并且发现此链接覆盖路由
As per the description, I could create class like below 根据描述,我可以创建如下的类
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;
}
}
However, this overriding needs to also be registered. 但是,此替代也需要注册。 From the link it shall be done in WebAPIConfig as below 通过链接,应在WebAPIConfig中完成,如下所示
configuration.Services.Replace(typeof(IHttpControllerSelector), new HttpNotFoundAwareDefaultHttpControllerSelector(configuration));
However I am not sure, how I could register the overriding in .Net Core Startup.cs file? 但是我不确定,如何在.Net Core Startup.cs文件中注册覆盖? as there is no Replace attribute available for Services. 因为没有“服务”可用的“替换”属性。
Can anybody help? 有人可以帮忙吗?
For capturing 404
and return custom error, you could try UseStatusCodePages
like 为了捕获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.