Web API小写路由

use*_*609 17 asp.net routes url-routing asp.net-web-api

那里,

我需要在我的Web API项目中强制使用Lowercase路由.如果它是一个MVC项目,我会使用类似的东西

routes.LowercaseUrls = true;
Run Code Online (Sandbox Code Playgroud)

但是在Web API中,属性不存在.

我尝试了LowercaseRoutesMVC4 NuGet扩展,但我的路由需要有一个自定义处理程序,以便扩展不会帮助我.

我能做什么?

Raj*_*njh 7

这看起来像你需要的

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { url = new LowercaseRouteConstraint() }
        );
    }
}

public class LowercaseRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var path = httpContext.Request.Url.AbsolutePath;
        return path.Equals(path.ToLowerInvariant(), StringComparison.InvariantCulture);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在https://gist.github.com/benfoster/3274578#file-gistfile1-cs-L4找到了这个