简体   繁体   English

WebAPI C#路由

[英]WebAPI C# Routing

I have two end points: 我有两个终点:

  • api/v1/user/session (For creating user login with post request ) api/v1/user/session (用于通过发布请求创建用户登录名)
  • api/v1/user (For creating user with post request) api/v1/user (用于使用发布请求创建用户)

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 所有的获取,发布,更新,补丁操作都可以在api / v1 / user / session端点中完成

all get,post,update, patch operations can be done in api/v1/user endpoint 所有的获取,发布,更新,补丁操作都可以在api / v1 / user端点中完成

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. 现在,我希望所有其余请求都可用于具有[httpPost],[httpGet]等属性的Session方法。

       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. 请注意,由于它是默认设置,因此从技术上讲您不需要[HttpPost] ,但是为了清楚起见,我将其包括在内。 You can add methods with the other Http verbs in the same way. 您可以以相同的方式将方法与其他Http动词一起添加。

I tried with hardcoded solution and it worked. 我尝试了硬编码的解决方案,它奏效了。 I added following route into the webapi.config file and it worked. 我将以下路由添加到webapi.config文件中,并且可以正常工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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