Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API Lowercase Route

Hy there,

I need to enforce Lowercase routes in my Web API project. If it was an MVC project i would use something like

routes.LowercaseUrls = true;

But in Web API that property does not exists.

I tried the LowercaseRoutesMVC4 NuGet extension but my routes needs to have a custom handler so that extension does not help me.

What can I do?

like image 281
user2219609 Avatar asked Apr 02 '13 15:04

user2219609


1 Answers

This looks like it does what you need

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);
    }
}

I found this at https://gist.github.com/benfoster/3274578#file-gistfile1-cs-L4

like image 174
Rajdeep Dosanjh Avatar answered Sep 18 '22 14:09

Rajdeep Dosanjh