Zapnologica
Zapnologica

Reputation: 22566

Asp.net web api routing to be like mvc site

How can I add a route so that my controllers will work similar to a mvc web appliation.

Because the default way that they have configured the routes will end up with you having so many controllers.

I just want to have a controller called Auth,

and then in my web API be able to call api/auth/login or api/auth/logout etc. Because with the default routing I will have to create a controller for login and one for logout.

So then I would have my Controller like so:

public class AuthController : ApiController
{

    [HttpPost]
    public IEnumerable<string> Login()
    {
        return new string[] { "value1", "value2" };
    }

    [HttpGet]
    public HttpMessageHandler Logout()
    {
        return new HttpMessageHandler.
    }
}

Upvotes: 1

Views: 218

Answers (1)

Ben Foster
Ben Foster

Reputation: 34830

The default Web API route uses the http method to determine the action to select. For example POST api/auth would look for an action named Post on AuthController.

If you want to use RPC style routing (like MVC) you need to change the default route to:

    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

Now POST api/auth/login will look for an action named Login on AuthController.

Upvotes: 2

Related Questions