路由到不同的WebAPI控制器的操作,其中存在可选的路由参数

时间:2016-03-16 17:01:31

标签: c# asp.net-mvc asp.net-web-api

我的MVC 4项目API路由配置如下:

WebApiConfig.cs:

  public static class WebApiConfig
  {
    public static void Register(HttpConfiguration config)
    {
        var company = System.Configuration.ConfigurationManager.AppSettings["DbCompany"];
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "MyApp/"+ company +"/{id}",
            defaults: new { controller = "main" , id = RouteParameter.Optional }
       );
       config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

 }

和MainController.cs包含以下方法:

    public JToken Get(string id)
    {
        ...
    }

    public JToken Get()
    {
        ...
    }

    [HttpPost]
    public JToken DoQuery([FromBody] String query)
    {
        ...
    }

    public void Post([FromBody] JObject JsonObject)
    {
       ...
    }

我想要达到的任何路线都不是:

     route: /MyApp/MyComp/DoQuery
     method: POST 
     ContextType: text/plain 
     Returns: JToken 

使用主控制器的正常Get / Post 否则在主控制器中使用DoQuery。

1 个答案:

答案 0 :(得分:0)

似乎所有缺少的是要映射到DoQuery的特殊情况路线。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var company = System.Configuration.ConfigurationManager.AppSettings["DbCompany"];

        config.Routes.MapHttpRoute(
            name: "DoQuery",
            routeTemplate: "MyApp/"+ company +"/DoQuery",
            defaults: new { controller = "main", action = "DoQuery" }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "MyApp/"+ company +"/{id}",
            defaults: new { controller = "main" , id = RouteParameter.Optional }
        );
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
    }

}