HttpGet Action不会被调用

时间:2017-12-24 00:33:15

标签: c# asp.net-core asp.net-core-routing

Startup.cs,锅炉板:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

我有一个控制器类,MembersController。

[Produces("application/json")]
[Route("api/Members")]
public class MembersController : Controller
{
    [HttpGet("{email},{password}")]
    [Route("api/members/authenticate/")]
    public async void Authenticate(String email, String password)
    {
        ///the method that won't fire
    }


    // GET: api/Members/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetMember([FromRoute] int id)
    {
        ///the boiler plate method that gets called
    }
}

基本上我尝试添加一个方法Authenticate,我在其中usernamepassword。我设置了一个路由和一些HTTPGet参数。但无论我多么惹它(前往http://localhost:64880/api/members/authenticate/,作为一个例子),我无法获得我添加的Authenticate方法来调用它。

我想这是路由的事情?

1 个答案:

答案 0 :(得分:6)

你正在混合路线。

假设您将控制器装饰有[Route("api/Members")]作为路由前缀,然后使用[Route("api/members/authenticate/")]进行操作,则该操作的结果路由为api/Members/api/members/authenticate/。看看你试图打电话的区别?

通常,您希望对身份验证操作执行POST,以便允许将参数发送到请求正文中的操作。

创建一个模型来保存数据

public class AuthModel {
    public string email { get; set; }
    public string password { get; set; }
}

接下来修复路线。您似乎正在使用属性路由,还混合了路由属性和http谓词属性的路由模板。

来自评论

  

此外,[Produces("application/json")]完全没有意义,因为JSON是默认的

[Route("api/Members")]
public class MembersController : Controller {

    //Matches POST api/members/authenticate
    [HttpPost("authenticate")]
    public async Task<IActionResult> Authenticate([FromBody] AuthModel model) {
        String email = model.email;
        String password = model.password

        //fake async task
        await Task.Delay(1);

        return Ok();
    }

    // GET: api/Members/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetMember([FromRoute] int id) {
        ///the boiler plate method that gets called

        //fake async task
        await Task.Delay(1);

        return Ok();
    }

}

参考Routing to Controller Actions