Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApi 2 POST with single string parameter not working

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)

like image 513
Danny Avatar asked Jun 15 '16 17:06

Danny


People also ask

Can we have multiple post method in Web API?

Open your controller class, in our project its ValuesController. cs >> Copy paste below code, these are two sample post methods with a string input and return parameter – you can write your business logic in it. Similarly, you can add any number of POST, GET, PUT, DELETE methods in one controller.

Can we use FromBody with Httpget?

Please note that we are able to send [FromBody] parameter in HTTP GET Request input.

How do I pass a class object as parameter in web API?

Show activity on this post. MakeUser method in the User controller for creating a username and password. UserParameter class for sending the parameters as an object. RunAsync method in console client.


2 Answers

c#

public class ValuesController : ApiController {     // POST api/values     [HttpPost] // added attribute     public IHttpActionResult Post([FromBody] string filterName) // added FromBody as this is how you are sending the data     {         return new JsonResult<string>(filterName, new JsonSerializerSettings(), Encoding.UTF8, this);     } 

JavaScript

$.ajax( {     url: "/api/Values/", // be consistent and case the route the same as the ApiController     type: "POST",     dataType: 'json',     data: "=Dirty Deeds", // add an = sign     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);     } }); 

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.

contentType: 'application/x-www-form-urlencoded' 

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.

public class Filter {     public string FilterName {get;set;} }  public class ValuesController : ApiController {     // POST api/values     [HttpPost] // added attribute     public IHttpActionResult Post([FromBody] Filter filter) // added FromBody as this is how you are sending the data     {         return new JsonResult<string>(filter.FilterName, new JsonSerializerSettings(), Encoding.UTF8, this);     } 

JavaScript

$.ajax( {     url: "/api/Values/", // be consistent and case the route the same as the ApiController     type: "POST",     dataType: 'json',     contentType: 'application/json',     data: JSON.stringify({FilterName: "Dirty Deeds"}), // send as json     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);     } }); 
like image 168
Igor Avatar answered Sep 27 '22 22:09

Igor


Add [FromBody] to the API method signature like public IHttpActionResult Post([FromBody]string filterName) and wrap the ajax data parameter with quotes: data: '"' + bodyContent + '"'.

Not very intuitive, but it works.

like image 38
misha Avatar answered Sep 27 '22 20:09

misha