使用Route属性触发错误的端点

时间:2017-12-07 19:13:48

标签: .net asp.net-web-api asp.net-web-api2 asp.net-web-api-routing

我的UserController中有以下方法。前两个,RegisterVerifyUser工作正常。

但是 - 我无法登录进行呼叫。无论我尝试使用哪种URL组合 - Register方法都会触发。

[RoutePrefix("api/user")]
public class UserController : ApiController
{
    [Route("Register")]
    [HttpPost]
    public HttpResponseMessage Register([FromBody]RegisterUserModel model)
    {
        ....
    }

    [HttpGet]
    [Route("{email}/{verifyId}")]
    public HttpResponseMessage VerifyUser(string email, string verifyId)
    {
        ....
    }

    [Route("Login")] //Not being fired - Register being fired
    [HttpPost]
    public HttpResponseMessage Login([FromBody]RegisterUserModel userMod)
    {
        ....
    }
}

我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:1)

发生的事情是您很可能只有基于默认约定的路线

// Convention-based routing.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

将首先映射到注册,而无需检查Login

调用api/user/Login将映射到api/{controller}/{id}约定路由,Login映射到id占位符。路由表使用HTTP谓词POST来查找可以使用提供的正文处理帖子的第一个操作。它会首先找到注册并映射到该动作。

检查以确保在WebApiConfig

中启用了属性路由
// Attribute routing.
config.MapHttpAttributeRoutes();

// Convention-based routing.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

以下评论显示了映射到操作的网址。

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

    //Matches POST api/user/register
    [Route("Register")]
    [HttpPost]
    public IHttpActionResult Register([FromBody]RegisterUserModel model) {
        //....
    }

    //Matches GET api/user/some_email/some_id
    [HttpGet]
    [Route("{email}/{verifyId}")]
    public IHttpActionResult VerifyUser(string email, string verifyId) {
        //....
    }

    //Matches POST api/user/login
    [Route("Login")]
    [HttpPost]
    public IHttpActionResult Login([FromBody]RegisterUserModel userMod) {
        //....
    }
}

参考Attribute Routing in ASP.NET Web API 2