noobiehacker noobiehacker - 1 month ago 14
ASP.NET (C#) Question

ASP.net WebAPI controller directory/ routing

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

Answer

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") };
    }
}
Comments