HttpGet Action不会被调用

问题描述 投票:1回答:1

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方法来调用。

我想这是一个路由的事情?

c# asp.net-core asp.net-core-routing
1个回答
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谓词属性的路由模板。

来自评论

此外,由于JSON是默认值,因此[Produces("application/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

© www.soinside.com 2019 - 2024. All rights reserved.