I have the following controller:
public class ValuesController : ApiController
{
// POST api/values
public IHttpActionResult Post(string filterName)
{
return new JsonResult<string>(filterName, new JsonSerializerSettings(), Encoding.UTF8, this);
}
}
WebApi config
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
I use this js code to call the api
$.ajax(
{
url: "/api/values/",
type: "POST",
dataType: 'json',
data: { filterName: "Dirty Deeds" },
success: function (result) {
console.log(result);
},
error: function (xhr, status, p3, p4) {
var err = "Error " + " " + status + " " + p3;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).message;
console.log(err);
}
});
I get a 405 method not allowed (post)
c#
JavaScript
Explanation
Because you are only sending a single value add the = sign in front of it so it will be treated like forms encoding. You can also add the content type if you want to make it clear that this is what you are doing to the ajax call.
Alternatively you could also send the content via URL OR wrap the content in an object on the server as well as in the ajax call and stringify it.
JavaScript
Add
[FromBody]
to the API method signature likepublic IHttpActionResult Post([FromBody]string filterName)
and wrap the ajax data parameter with quotes:data: '"' + bodyContent + '"'
.Not very intuitive, but it works.
Add [HttpPost] attribute to method in controller