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
,在其中使用一个username
和password
。我设置了一条路由和一些HTTPGet参数。但是不管我有多烦(以http://localhost:64880/api/members/authenticate/
为例),我都无法获取添加的Authenticate方法来调用。我想这是路由的东西吗?
最佳答案
您正在混合路线。
假定您已将控制器装饰为[Route("api/Members")]
作为路由前缀,然后使用[Route("api/members/authenticate/")]
装饰了操作,则该操作的最终路由将为api/Members/api/members/authenticate/
。看到与您尝试拨打的电话有所不同了吗?
通常,您可能希望对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
关于c# - HttpGet Action没有被调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47957177/