1

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.
 }
}
asked Mar 4, 2014 at 13:02

1 Answer 1

2

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.

answered Mar 4, 2014 at 13:04

7 Comments

Then do i just specify the Get, POST, etc as a filter type as in mvc?
You can't do HTTP method based routing in MVC, you have to specify the action name. You use the [HttpGet/HttpPost] filters to constrain the type of requests that the Action can handle not whether it will actually match the route.
So then How do I specify in the controller if it will be a get or Post? see my edit
Ok, but then how would I have a controller called login that can service a GET and a POST . Is that possible?
Yes, this is the default behaviour or Web API (not what you're asking in your question). Create a new LoginController with actions Get/Post. Please start a new post if your question has changed, rather than changing your current one.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.