ASP.NET Web API 2 - POST / jQuery

I am trying to send an object to a server where I am using Web API 2. The code is as follows:

$.ajax({ cache: false, type: "POST", url: "/api/Employees", data: { EmployeeId: 1 }, success: function(result) { console.log("employees saved successfully"); }, error: function(result) { } }); 

Regarding the web API:

 public class EmployeesController : ApiController { // POST api/<controller> public void Post([FromBody]Employee value) { } } public class Employee { public Int32 EmployeeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string JobTitle { get; set; } public DateTime BirthDate { get; set; } public DateTime HireDate { get; set; } public ReferenceData MaritalStatus { get; set; } public Int32 VacationDays { get; set; } public Int32 SickLeaveDays { get; set; } public decimal Salary { get; set; } public string Cid { get; set; } } 

I get this response from the server

 The requested resource does not support http method 'POST' 
+1
source share
3 answers

This is because of how API routing works. He is / api / NameOfController / NameOfMethod. Your controller name is Employee, and your method name is Post. If you want to switch to this method, you need to do / api / Employee / Post. This is why / api / Employees / SaveEmployee works great when changing a method name (for your comment from yesterday).

0
source

You need to put the [httppost] annotation on the controller

 public class EmployeesController : ApiController { // POST api/<controller> [HttpPost] public void Post([FromBody]Employee value) { } } 

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Halfway down the page in the HTTP Methods section

0
source

Is it possible that your routing related WebApiConfig.Register method has an atypical or custom configuration? There is no need to add the [HttpPost] metadata attribute when ApiController uses the RESTful convention for action names. Similarly, the [FromBody] attribute is not required when the parameter is a complex type. By default, WebApi will look at the request body and use the correct MediaTypeFormatter (XML, JSON, FormUrlEncoded). The following is the default list of WebApiConfig.Register. If you made a change, can you revert to the WebApiConfig.Register standard, remove the metadata attributes, and then repeat?

  public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } 
0
source

All Articles