如何在 ASP.NET 5 路由中传递无效值时获取验证消息
how I can get validation message while passing invalid value in ASP.NET 5 routing
我有这个路由
[HttpGet("{check_id:long:min(1)}")]
在 check_id 中传递 0 值时,它会给出 404
响应代码,这非常有效。
但我也想要一个消息作为回应。我该如何实施?
据我所知为什么路由匹配失败的原因没有暴露在ASP.NET核心路由中间件之外,只记录了,所以我认为不是可以根据您感兴趣的特定原因(在本例中为路由参数约束)使用自定义代码对路由匹配失败做出反应。
一个解决方案,虽然有点 hacky,但可以像这样实现您自己的自定义中间件(您必须调整控制器和参数名称):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... code skipped
app.UseRouting();
// put this after the .UseRouting() or .UseAuthorization() call
app.Use(async (context, next) =>
{
if (context.Request.Path.Value.StartsWith("/WeatherForecast")) // controller name
{
var end = context.GetEndpoint();
if (end == null) // if the endpoint is null it means that the route matching failed (wrong path OR route parameter constraint failure)
{
// you could put more logic here to get the route parameter and check if it's valid or not
context.Response.StatusCode = 404;
await context.Response.WriteAsync("You supplied a wrong parameter");
return; // short circuit pipeline
}
}
await next.Invoke();
});
// ... code skipped
}
更多信息可以参考负责路由选择的中间件和匹配器类的代码:
我有这个路由
[HttpGet("{check_id:long:min(1)}")]
在 check_id 中传递 0 值时,它会给出 404
响应代码,这非常有效。
但我也想要一个消息作为回应。我该如何实施?
据我所知为什么路由匹配失败的原因没有暴露在ASP.NET核心路由中间件之外,只记录了,所以我认为不是可以根据您感兴趣的特定原因(在本例中为路由参数约束)使用自定义代码对路由匹配失败做出反应。
一个解决方案,虽然有点 hacky,但可以像这样实现您自己的自定义中间件(您必须调整控制器和参数名称):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... code skipped
app.UseRouting();
// put this after the .UseRouting() or .UseAuthorization() call
app.Use(async (context, next) =>
{
if (context.Request.Path.Value.StartsWith("/WeatherForecast")) // controller name
{
var end = context.GetEndpoint();
if (end == null) // if the endpoint is null it means that the route matching failed (wrong path OR route parameter constraint failure)
{
// you could put more logic here to get the route parameter and check if it's valid or not
context.Response.StatusCode = 404;
await context.Response.WriteAsync("You supplied a wrong parameter");
return; // short circuit pipeline
}
}
await next.Invoke();
});
// ... code skipped
}
更多信息可以参考负责路由选择的中间件和匹配器类的代码: