Thursday, October 6, 2016

Creating lowercase routes in ASP.NET Web API

When it comes to creating lowercase routes in ASP.NET Web API, there is no built-in facility to automatically lowercase all of your routes as is the case with ASP.NET MVC.

However, you can still solve this issue without resorting to Attribute-based routing and manually writing all of your routes in lowercase.

This can be accomplished through Custom Route Constraints.  In this instance, you will want to create a Custom Route Constraint which simply translates all of the default ASP.NET Web API routes into their corresponding lowercase version.

You can write a LowercaseRouteConstraint as follows:


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);
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment