2017-07-25 78 views
0

我想在我的控制器中有兩個Web API方法。其中一個用於在標題中使用MyViewModel對象調用GET,另一個則不使用。GET和無參數GET導致AmbiguousActionException?

MyController.cs:

[Produces("application/json")] 
[Route("api/[controller]")] 
public class MyController : Controller 
{ 
    [HttpGet] 
    public IEnumerable<UserModel> Get() 
    { 
     // ... 
    } 

    [HttpGet] 
    public IEnumerable<UserModel> Get(MyViewModel viewModel) 
    { 
     // ... 
    } 
} 

但瀏覽到Chrome中的路由地址不傳遞任何MyViewModel給了我這個錯誤:

AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

MyController.Get (MyProject)

MyController.Get (MyProject)

如果我註釋掉的參數方法,把一個破發指向參數化函數並瀏覽到api URL,它看起來像是viewModelnull就像我預料的那樣,它似乎是一個新的MyViewModel對象用參數1 ess構造函數。似乎它可能與我的問題有關。

我對Microsoft.AspNetCore V1.1.2Microsoft.AspNetCore.Mvc V1.1.3運行。

回答

2

將屬性路由添加到其中的一個。 例如:

[HttpGet("/myaction")] 
    public IEnumerable<UserModel> Get(MyViewModel viewModel) 
    { 
    // ... 
    } 

或將其添加到所有的人。 MVC無法區分兩種方法,因爲viewModel可能爲空,並且不知道它是否應該先匹配action或其他。

1

One for when GET is called with a MyViewModel object in the header, and one without.

在ASP.NET核心Model Binding默認使用的查詢參數爲源模型的人口,而不是頭。如果您需要從頭部填補MyViewModel,使用[FromHeader]屬性:

public IEnumerable<UserModel> Get([FromHeader] MyViewModel viewModel) 

ASP.NET核心routing實現不使用標頭路由解決。正如您使用屬性路由,正如@Vlado所說的,您需要使用不同的路由名稱來消除歧義行爲。