区分ASP.NET WEB API中包含查询字符串的Get方法

时间:2014-07-16 07:39:17

标签: asp.net-web-api asp.net-web-api-routing

我有一个包含以下获取方法的ASP.NET Web Api:

[RoutePrefix("api/contact")]
public class ContactController : ApiController
{
    private ContactContext db = new ContactContext();

    public IEnumerable<Contact> Get()
    {
        return db.Contacts.AsEnumerable();
    }



    [Route("{id:int}")]
    public Contact Get(int id)
    {
        var result = db.Contacts.Find(id);
        if (result == null)
        {


            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return result;
    }

    public IEnumerable<Contact> GetContacts([FromUri]Filter filter)
    {
        return db.Contacts.Where(c => c.DepartmentId == filter.DepartmentId && c.City == filter.City).ToList();
    }
}

在功能public IEnumerable<Contact> GetContactsfilter([FromUri]Filter filter) DepartementId&amp; City位于查询字符串中,如

localhost:12345/api/Contact?DepartmentId=2&city=Mumbai

我的问题是如何为查询添加属性路由,因为 目前它无法区分获取方法并返回错误

{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nSystem.Collections.Generic.IEnumerable`1[MyFirstWebApi.Models.Contact] Get() on type MyFirstWebApi.Controllers.ContactController\r\nSystem.Collections.Generic.IEnumerable`1[MyFirstWebApi.Models.Contact] GetContacts(MyFirstWebApi.Models.Filter) on type MyFirstWebApi.Controllers.ContactController","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"}

我尝试将路由属性添加到包含id的Get方法,但这不起作用。

1 个答案:

答案 0 :(得分:2)

属性路由或常规路由不支持模板中的查询参数。相反,您可以将控制器修改为只有两个操作,如下所示:

// Here if no DepartmentId or City are provided, then the 'filter' parameter would be null
[Route]
public IEnumerable<Contact> GetContacts([FromUri]Filter filter)

[Route("{id:int}")]
public Contact Get(int id)