Reputation: 1220
I have a ASP.NET Web Api Containing following Get Methods:
[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();
}
}
In function public IEnumerable<Contact> GetContactsfilter([FromUri]Filter filter)
DepartementId & City are in Query String like
localhost:12345/api/Contact?DepartmentId=2&city=Mumbai
My Question is how do I add Attribute Routing for Query,because Currently it cannot differentiate between the Get Methods and is returning error
{"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()"}
I tried adding the Routing Attribute to Get method containing id
but that doesn't worked.
Upvotes: 0
Views: 750
Reputation: 57979
Attribute routing or regular routing does not support query parameters in the templates. Instead you could modify your controller to just have two actions as below:
// 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)
Upvotes: 2