Reputation: 1109
I am trying to do something similar to what is suggested on this site https://mathieu.fenniak.net/stop-designing-fragile-web-apis/
It suggested that this is a better url
http://api.fbi.gov/wanted/most
My question is how do I do something like that in ASP.NET WEBAPI. For example, if I want to return a specific query of joining some data with another table, instead of passing in a parameter I just want a method url call that just does the one query I want. What is the easiest way to accomplish this task?
example url call:
api/controller/joinresultwithtable2
Upvotes: 1
Views: 2325
Reputation: 13
You can also use following method:
[ActionName("DefaultApi")]
[Route("Api/UserLogin/DefaultApi/UserDetails")]
public IHttpActionResult UserDetails(){
return Ok(db.UserLogins.ToList());
}
Upvotes: 0
Reputation: 142044
It's not exactly pretty but you can setup routing so a specific path maps to a specific controller and action.
config.Routes.MapHttpRoute("query1", "query/query1", new {controller="StockQueries", action="query1"});
config.Routes.MapHttpRoute("query2", "query/query2", new { controller = "StockQueries", action = "query2" });
config.Routes.MapHttpRoute("query3", "query/query3", new { controller = "StockQueries", action = "query3" });
And then have a controller that looks like this,
public class StockQueriesController : ApiController
{
[ActionName("query1")]
public HttpResponseMessage GetQuery1()
{
return new HttpResponseMessage() {Content = new StringContent("Query1")};
}
[ActionName("query2")]
public HttpResponseMessage GetQuery2()
{
return new HttpResponseMessage() { Content = new StringContent("Query1") };
}
[ActionName("query3")]
public HttpResponseMessage GetQuery3()
{
return new HttpResponseMessage() { Content = new StringContent("Query1") };
}
[ActionName("query4")]
public HttpResponseMessage GetQuery4()
{
return new HttpResponseMessage() { Content = new StringContent("Query1") };
}
}
Upvotes: 2
Reputation: 13176
If you are using ASP.NET Web API 2, you can do the following:
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
Source: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Upvotes: 2
Reputation: 28737
The easiest way to go is probably attribute routing. You can find more information here: http://attributerouting.net/
It allows you to declare any route right (with parameters) directly on an action method. That way you can control quite easily how you make your resources available.
In case you want to version your API, it's also quite easy, because you can just include the version in your attribute
Upvotes: 2