WebApi HTTPPOST Endpoint not being hit

2020-03-31 07:46发布

问题:

I have the following simple HTTPPOST endpoint;

[AllowAnonymous]
[HttpPost]
[Route("forgotPassword")]
public IHttpActionResult ForgotPassword(string userName, string callbackUrl)

Where the controller is decorated as follows;

[Authorize]
[RoutePrefix("api/accounts")]
public class AccountsController : ApiController

Now when i try to test this endpoint in postman, using the following url;

http://localhost:11217/api/accounts/forgotPassword

with the strings in the body of the message

I get the following return.

{ "Message": "No HTTP resource was found that matches the request URI 'http://localhost:11217/api/accounts/forgotPassword'.",
"MessageDetail": "No action was found on the controller 'Accounts' that matches the request." }

Now I would rather not have to create a model for the two strings (if possible). Also if I try to put the params in the query string I get a potantially dangerous request response

http://localhost:11217/api/accounts/forgotPassword/test&callbackUrl=local

Can anyone help please?

回答1:

If you want to send mulitple parameters when doing a post request you should create a DTO that contains the parameters as

public class forgetPasswordDTO
{
    public string userName { get; set; }
    public string callbackUrl { get; set; }
}

Then add the DTO as a method parameter with the [FromBody]

[AllowAnonymous]
[HttpPost]
[Route("forgotPassword")]
public IHttpActionResult ForgotPassword([FromBody] forgetPasswordDTO data)

And in you client, create the object as

var data = {
    'userName': user,
    'callbackUrl': url
};

And add it to the body of the request.

Here's a nice article about this topic