Reputation: 9818
I am building an angularJS application with a asp.net webapi backend. In my routeconfig file, i have this
routes.MapRoute(
name: "default",
url: "{*url}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
This works fine. Any Url that is called is returned the Home/Index view (the only view i have) to the application, and angularJS works out if there is a querystring and works out which state to show.
I have the basic Get, Put, Post and Delete methods in my WebApi, and i can call them fine. Examples are
public class CompanyController : ApiController
{
private CompanyService _service;
public CompanyController(CompanyService service)
{
_service = service;
}
public async Task<IHttpActionResult> Get()
{
...
return Ok(model);
}
public async Task<IHttpActionResult> Get(int id)
{
...
return Ok(model);
}
public async Task<IHttpActionResult> Post(CompanyModel model)
{
...
return Ok();
}
public async Task<IHttpActionResult> Put(Company model)
{
...
return Ok();
}
public async Task<IHttpActionResult> Delete(CompanyModel model)
{
...
return Ok();
}
}
Now i would like to add another method to my api, where the user can load companies, but also pass in a term to search for (a string), a pageSize (int) and a page number (int). Something like this
public async Task<IHttpActionResult> Get(string term, int page, int pageSize) {
...
return Ok(results);
}
Now i understand that i need to add another route, to make sure this method can be called. Fine, so i add this to my RouteConfig.
// search
routes.MapRoute(
name: "search",
url: "api/{controller}/{page}/{pageSize}/{term}",
defaults: new { page = @"\d+", pageSize = @"\d+", term = UrlParameter.Optional }
);
Why doesnt this work?? I got a resource cannot be found error, when trying to call it via postman using the url localhost/api/company/1/10/a, where 1 = page, 10 = pageSize and a = term
Its probably a simple answer, but new to MVC so still learning.
Upvotes: 0
Views: 818
Reputation: 4130
1- You are using Get method, which means you can pass your search option via Url, so you can create a search option object like :
public class SearchOptions
{
public string Term{get; set;}
public int Page {get; set;}
public int PageSize {get; set;}
}
then you can change your method to be like this
[HttpGet]
[Route("api/blabla/SearchSomething")]
public async Task<IHttpActionResult> Get([FromUri]SearchOptions searchOptions) {
...
return Ok(results);
}
Notice the Route attribute that I've decorated the method by, you can use different constraints for the method parameters, have a look at this.
Finally you can call the method from the client like this
api/blabla/SearchSomething?term=somevalue&page=1&pageSize=10
Hope that helps.
Upvotes: 1