4

I have a WebAPI controller

public class MyController : ApiController
{
    [HttpPost]
    public SomeResult MyAction(string name, string message)
    {
        return SomeResult.???;
    }
}

I have an angular controller calling this method

$http
    .post("/api/My/MyAction", { name: "bob", message: "hello" })
    .then(function(xhr) { ... }, function(xhr) { ... });

I get this result

Server Error in '/' Application.

The resource cannot be found.

What did I do wrong?

P.S. It's not the URL...It works when I use HttpGet and append the parameters to the query string.

Community
  • 1
  • 1
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313

2 Answers2

2

I've faced that problem, if you google there are different ways to solve it. One of the easiest requires to use only one input object in you WebApi controller, so in you case just crate a class

public class InputData {
    public string name { get; set; }
    public string message { get; set; }
}

Then change your input to the new create object with [FromBody] prefix (maybe not mandatory, see @ADyson comment)

public SomeResult MyAction([FromBody]InputData inputData)
Naigel
  • 9,086
  • 16
  • 65
  • 106
  • `[FromBody]` should not be necessary for a complex type such as this. It's only required when you try to pass a simple type (e.g. string) in the body. See https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api – ADyson Nov 11 '16 at 12:18
  • @ADyson thank you for the suggestion, from your link it seems reasonable that it's not mandatory – Naigel Nov 11 '16 at 12:21
2

For more than one attribute for post requests, you can use [FromBody] in your controller and make a ViewModel class. Example:

[HttpPost]
        public HttpResponseMessage UpdateNumber([FromBody]UpdateNumberViewModel model)
        {
           //To do business
            return Request.CreateResponse(HttpStatusCode.OK);
        }

UpdateViewModel:

public class UpdateViewModel
    {
        public int Id{ get; set; }
        public string Title{ get; set; }

    }

Angular:

var model = {                    
                    Id: 1,
                    Title: 'Vai filhão'
                }

    $http.post('/api/controller/updateNumber/',model).then(function () { alert("OK"); }, function () {alert("something wrong"); });

You can see more details about how web api it works here: https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

  • 1
    similar to another answer on here, `[FromBody]` should not be necessary for a complex type such as this. It's only required when you try to pass a simple type (e.g. string) in the body. See https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api – ADyson Nov 11 '16 at 12:24
  • Exactly. i'll edit my answer... – Kleyton Santos Nov 11 '16 at 12:27