2013-04-02 109 views
15

Hy there,Web API小寫路由

我需要在Web API項目中強制使用小寫路由。 如果它是一個MVC項目,我會使用類似

routes.LowercaseUrls = true; 

,但在Web API該屬性不存在。

我嘗試了LowercaseRoutesMVC4 NuGet擴展,但我的路由需要一個自定義處理程序,以便擴展不能幫助我。

我該怎麼辦?

+2

你有沒有嘗試過這個路線限制? https://gist.github.com/benfoster/3274578 – AardVark71

回答

6

這看起來像它你需要什麼

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

,我發現這個在https://gist.github.com/benfoster/3274578#file-gistfile1-cs-L4

-1

我JSON配置像

public class JsonConfig 
{ 
    public static void Initiliaze(HttpConfiguration config, bool isCamelCase) 
    { 
     var json = config.Formatters.JsonFormatter; 
     json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; 
     json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 
     json.SerializerSettings.Formatting = Formatting.None; 

     if (isCamelCase) 
      json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

     config.Formatters.Remove(config.Formatters.XmlFormatter); 
    } 
} 

你可以像WebApiConfig.cs調用此方法

JsonConfig.Initiliaze(config, true);