c# - 如何在 ASP.NET 5 路由中传递无效值时获取验证消息
问题描述
我有这个路由
[HttpGet("{check_id:long:min(1)}")]
在 check_id 中传递 0 值时,它会给出404
响应代码,这是完美的工作。
但我也想要一条消息作为回应。我该如何实施?
解决方案
As far as I know the reason of why a route match fails is not exposed outside the ASP.NET Core routing middleware, only logged, so I think it's not possible to react with custom code to the route matching failure with the specific reason you are interested in (route parameter constraint in this case).
A solution, although a little bit hacky, could be to implement your own custom middleware like so (you have to adapt controller and parameter names):
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
}
For more info, you can refer to the code of the Middleware and Matcher classes responsible of route selection:
推荐阅读
- azure - MS Teams 聊天机器人自定义授权
- typescript - 类验证器是如何工作的?
- luigi - 带有单独任务的 Luigi 依赖项规范问题
- powershell - 文件中的 SecureString“随机”停止工作
- sas - SAS将数字变量覆盖为字符
- java - Jira ServiceDesk 用户创建 - 此资源需要 WebSudo
- reactjs - 在反应导航 v5 中传递道具的问题
- java - 在 Java Lambda 中无法使用 Reddison 客户端(使用 samLocal 和 localstack)
- sql - 可以使用 Where 子句进行拆分,批量拆分和导出表
- javascript - 限制 HTML 的用户输入当前时间之后