首页 > 解决方案 > 如何在 ASP.NET 5 路由中传递无效值时获取验证消息

问题描述

我有这个路由

[HttpGet("{check_id:long:min(1)}")]

在 check_id 中传递 0 值时,它会给出404响应代码,这是完美的工作。

但我也想要一条消息作为回应。我该如何实施?

标签: c#asp.net.netasp.net-coreasp.net-core-webapi

解决方案


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:

EndpointRoutingMiddleware.cs

DfaMatcher.cs


推荐阅读