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:
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
No comments:
Post a Comment