简体   繁体   中英

WebAPI C# Routing

I have two end points:

  • api/v1/user/session (For creating user login with post request )
  • api/v1/user (For creating user with post request)

How to route this two endpoints in same controller? I also want to specify action for a specific request. More clearly:

all get,post,update, patch operations can be done in api/v1/user/session endpoint

all get,post,update, patch operations can be done in api/v1/user endpoint

Is it possible ?

Example:

config.Routes.MapHttpRoute(
    "UserApi",
    "api/v1/{controller}/session",
    new { controller = "User", action="Session" });

Now, I want all rest requests to work for Session method with [httpPost],[httpGet] etc attributes.

       config.Routes.MapHttpRoute("lol", "api/v1/{controller}/session", 
            new { controller = "User", action="Session" });

        //config.Routes.MapHttpRoute(
        //    name: "LoginApi",
        //    routeTemplate: "api/v1/{controller}",
        //    defaults: new { controller = "User"}
        //);

        config.Routes.MapHttpRoute(
            name: "RailStationApi",
            routeTemplate: "api/v1/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

I would suggest you look at attribute routing - this is a lot easier to specify than using the central configuration.

[RoutePrefix("api/v1")]
public class UserController : ApiController {

    [HttpPost]
    [Route("user/session")]
    public void Login(/*...*/) {
        // ...
    }

    [HttpGet]
    [Route("user/session")]    // Note this has the same route as Login
    public SessionResult GetSession(/*...*/) {
        // ...
    }

    [HttpPost]
    [Route("user")]
    public void CreateUser(/*...*/) {
        // ...
    }

}

Note that you don't technically need [HttpPost] since it is the default, but I included it for clarity. You can add methods with the other Http verbs in the same way.

I tried with hardcoded solution and it worked. I added following route into the webapi.config file and it worked.

RouteTable.Routes.MapHttpRoute(
            name: "SessionApi",
            routeTemplate: "api/v1/user/session",
            defaults: new { Controller = "Session", id = RouteParameter.Optional }
        ).RouteHandler = new SessionStateRouteHandler();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM