Reputation: 484
I have this routing
[HttpGet("{check_id:long:min(1)}")]
while passing 0 value in check_id, it gives 404
response code, that's perfectly working.
But I also want a message in response. How can I implement it?
Upvotes: 0
Views: 181
Reputation: 86
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:
Upvotes: 2