简体   繁体   English

在Web API上调用post方法时获取404

[英]Getting 404 when calling a post method on Web API

I have an API controller which have standard GET,POST and Delete actions. 我有一个具有标准GET,POST和Delete操作的API控制器。

[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    //Get
    [HttpPost]
    public async Task Post([FromBody] TestUser testUser, string tempPassword, role = "Guest")
    {

    }
}

Now I am adding a new action using: 现在,我使用以下命令添加新操作:

[HttpPost]
[Route("api/[controller]/UpdateRole")]
public async Task Post(string email, List<string> roles)
{
}

When I am trying to call the API using postman , 当我尝试使用邮递员调用API时,

Type : POST Endpoint : http://localhost/api/users/UpdateRole 类型:POST端点: http:// localhost / api / users / UpdateRole

Request body: 要求正文:

{
    "email":"something@mail.com",
    "roles":["S1","s3"]
}

But I am getting a 404 as response back. 但是我得到了404作为回应。 On server I can see , 在服务器上,我可以看到,

the application completed without reading the entire request body. 无需阅读整个请求正文即可完成应用程序。

It seems that your overall route is /api/Users/api/Users/UpdateRoute because of how RouteAttribute works. 由于RouteAttribute工作原理,您的总体路由似乎是/api/Users/api/Users/UpdateRoute

[Route("a")]
public class MyController
{
    [Route("a/b")]
    public IActionResult MyAction()
    {
    }
}

The above will have a route of /a/a/b because the action route is appended to the controller route in this case. 上面的路由为/a/a/b因为在这种情况下,操作路由会附加到控制器路由。

Your options are: 您的选择是:

  • Change the controller route to [Route("[controller]/[action]")] and remove the action route, in which case the example above would become /MyController/MyAction 将控制器路由更改为[Route("[controller]/[action]")]并删除操作路由,在这种情况下,上例将变为/MyController/MyAction
  • Change the action route to simply [Route("b")] , in which case the full route would be a/b 将操作路线更改为简单的[Route("b")] ,在这种情况下,完整路线将为a/b
  • Use an absolute path for the action route [Route("/a/b")] , in which case the controller route would be ignored and the full route will simply be /a/b . 使用绝对路径作为操作路径[Route("/a/b")] ,在这种情况下,控制器路径将被忽略,而完整路径将只是/a/b

See here for more information about routing. 有关路由的更多信息,请参见此处

As for your issue with null values, ASP.NET Core is currently expecting email and roles as querystring parameters. 至于null值问题,ASP.NET Core当前期望将emailroles用作查询字符串参数。 Instead, you should create a model for your request body: 相反,您应该为请求主体创建一个模型:

public class MyModel
{
    public string Email { get; set; }
    public List<string> Roles { get; set; }
}

And then change your action to accept it: 然后更改您的操作以接受它:

[HttpPost]
[Route("api/[controller]/UpdateRole")]
public async Task Post([FromBody]MyModel model)
{

}

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

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