2016-08-01 27 views
3

我想有一個GET和同一個路由POST的WebAPI路由:結合屬性和HttpConfiguration設置

我已經註冊了以下內容:

config.MapHttpAttributeRoutes(); 

    config.Routes.MapHttpRoute(
       name: "MyGetMethod", 
       routeTemplate: "api/v1/users/{user}", 
       defaults: new 
           { 
            controller = "Users", 
            action = "MyGetMethod" 
           }, 
       constraints: null, 
       handler: HttpClientFactory.CreatePipeline(
        new HttpControllerDispatcher(config), 
        routeHandlerFactory.Create())); 

    config.Routes.MapHttpRoute(
       name: "MySetMethod", 
       routeTemplate: "api/v1/users/{user}", 
       defaults: new 
           { 
            controller = "Users", 
            action = "MySetMethod" 
           }, 
       constraints: null, 
       handler: HttpClientFactory.CreatePipeline(
        new HttpControllerDispatcher(config), 
        routeHandlerFactory.Create())); 

UsersController.cs包含:

[HttpPost] 
    public HttpResponseMessage MySetMethod(string user) 
    { 
     return new HttpResponseMessage(HttpStatusCode.NotImplemented); 
    } 


[HttpGet] 
    public HttpResponseMessage MyGetMethod(string user) 
    { 
     return new HttpResponseMessage(HttpStatusCode.NotImplemented); 
    } 

這是行不通的。 的GET工作正常,但是當我使用POST了的WebAPI仍然重定向到GET方法,我也得到了錯誤:

"Message": "The requested resource does not support http method 'POST'."

如果我註釋掉GET方法的註冊,則POST工作正常。

是因爲我在控制器方法上使用屬性[HttpPost],[HttpGet]之間的組合而不是將它們標記爲constraints

如何在同一條路線上有GETPOST

+0

什麼是Web方法有關使用一個方法與檢查'如果(HttpContext.Current.Request.HttpMethod == 「POST」)'? – Marusyk

回答

0

如果使用這種將工作

config.MapHttpAttributeRoutes(); 

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

我正在使用config.MapHttpAttributeRoutes();對不起,我忘了添加它。編輯了這個問題。不起作用 –

+0

請檢查這個http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api不需要單獨的帖子,並得到路由圖和在你的Controller使用routeMap屬性 – gurdeep

0

你只需要定義一個HttpRoute爲,請試試這個:

config.Routes.MapHttpRoute(
       name: "UserController", 
       routeTemplate: "api/v1/users/{user}", 
       defaults: new { user= RouteParameter.Optional } 
       handler: HttpClientFactory.CreatePipeline(
        new HttpControllerDispatcher(config), 
        routeHandlerFactory.Create())); 

如果仍然不能正常工作,請嘗試相同的代碼,但將routeTemplate更改爲:

routeTemplate: "api/v1/{controller}/{user}" 

並調用使用後,以

https://YourServer/YourVirtualDirectory/api/v1/Users/myUser 
+0

我也是這樣試過的,結果仍然是一樣的:(如果我從控制器方法移動HttpPost和HttpGet屬性並將它們作爲約束條件,它可以正常工作 但是,爲什麼' t我使用屬性? –

+0

您是否可以選擇使用AttributeRouting而不是基於約定的路由?我強烈建議如果是,我會發布您的答案 –

+0

您在第二個參數(HttRequestMessage)中也有一個類型,缺少'p' –