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 "/".

Resource is not found.

What have I done wrong?

PS This is not a URL ... It works when I use HttpGetand add parameters to the query string.

+4
source share
2 answers

For more than one attribute for mail requests, you can use [FromBody] in your controller and create 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"); });

, web api: https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

+2

, Google, . WebApi,

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

create [FromBody] (, , . @ADyson)

public SomeResult MyAction([FromBody]InputData inputData)
+2

Source: https://habr.com/ru/post/1660486/


All Articles