mr_coder
mr_coder

Reputation: 69

MVC Web API Post method with custom action name

And I wrote custom action names for ever process.

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
); 

In webapi config I wrote like this and in controller, I started like below

[System.Web.Http.HttpPost]
public HttpResponseMessage Control(List<string>codes,string updateperson,string refPeriod, int actualyear, int actualmonth)
{

For get methods, everything works well but for post method it doesn't work and gives error like below.

In body in post I send

{codes: ["CPM2018-004"], updateperson: "E3852", refPeriod: "SFC18", actualyear: 2018, actualmonth: 12}

Request URL:http://localhost:50941/Api/Investment/Control Request Method:POST Status Code:404 Not Found Remote Address:[::1]:50941 Referrer Policy:no-referrer-when-downgrade

How can I sreceive post requests to web API with custom action name?

Upvotes: 1

Views: 631

Answers (1)

Nkosi
Nkosi

Reputation: 247098

Create model to hold value being posted.

public class ControlViewModel {
    public List<string> codes { get; set; }
    public string updateperson { get; set; }
    public string refPeriod { get; set; }
    public int actualyear { get; set; }
    public int actualmonth { get; set; }
}

And then update the action to expect the data in the BODY of the request

public class InvestmentController : ApiController {

    [HttpPost]
    public HttpResponseMessage Control([FromBody]ControlViewModel data) {
        //...
    }

    //...
}

Reference Parameter Binding in ASP.NET Web API

Upvotes: 1

Related Questions