1

我正在開發ASP.NET MVC Web Api。我正在爲我的api重寫路由,以使網址整潔。但它不起作用。請參閱下面的我的場景。無法在ASP.NET MVC Web Api中配置或重寫路由

我在ItemsController中有這樣的操作方法。

public HttpResponseMessage Get([FromUri]string keyword = "", [FromUri]int category = 0, [FromUri]int region = 0, [FromUri]int area = 0, [FromUri]int page = 0,[FromUri]int count = 0) 
{ 
. 
. 
. 
} 

在WebApiConfig我配置路由像這方面的行動。

config.Routes.MapHttpRoute(
      name: "", 
      routeTemplate: "api/v1/places/{category}/{region}/{area}/{page}/{count}", 
      defaults: new { controller = "ItemsController" , keyword = "" , category = 0 , region = 0 ,area = 0 , page = 0 , count = 0 } 
     ); 

正如你所看到的,我沒有關鍵字路線設置。但是當我從下面的URL訪問,它給我錯誤。

這就是如何使GET請求

http://localhost:50489/api/v1/places/0/0/0/1/2 

這是錯誤

{ 
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:50489/api/v1/places/0/0/0/1/2'.", 
    "MessageDetail": "No type was found that matches the controller named 'ItemsController'." 
} 

所以請我怎麼能解決呢?我如何重寫它?我想在該網址中製作排除關鍵字。我還會爲此採取另一條路線。請問我該如何解決這個問題。

這是不行的。下面

config.Routes.MapHttpRoute(
       name: "", 
       routeTemplate: "api/v1/places/{keyword}/{category}/{region}/{area}/{page}/{count}", 
       defaults: new { controller = "ItemsController" , keyword = "" , category = 0 , region = 0 ,area = 0 , page = 0 , count = 0 } 
      ); 

回答

1

的錯誤指示你的控制器不存在。

這是因爲Web API正在尋找名爲ItemsControllerController的控制器。框架自動添加後綴Controller。所以,如果你的控制器實際上是命名爲ItemsController,你的路線應該是:

config.Routes.MapHttpRoute(
     name: "", 
     routeTemplate: "api/v1/places/{category}/{region}/{area}/{page}/{count}", 
     defaults: new { controller = "Items" , keyword = "" , category = 0 , region = 0 ,area = 0 , page = 0 , count = 0 } 
    ); 
+0

非常感謝。有效。 –

0

假人查詢嘗試使用此way..just做出相應的改變

API代碼:

[Route("api/{Home}/{Username}/{Password}")] 
     public HttpResponseMessage Get(string Username, string Password) 
     { 
//code here 
} 

WebApiConfig

public static void Register(HttpConfiguration config) 
     { 
      // Web API configuration and services 
      // Configure Web API to use only bearer token authentication. 
      config.SuppressDefaultHostAuthentication(); 
      config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 

      // Web API routes 
      config.MapHttpAttributeRoutes(); 


      config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

      config.Routes.MapHttpRoute(
      name: "ContactApi", 
      routeTemplate: "api/{controller}/{Username}/{Password}" 
      ); 


     }