series0ne series0ne - 28 days ago 6
AngularJS Question

ASP.NET WebAPI and Angular POST

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.

Answer

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