tutorial net example ejemplo asp javascript c# asp.net-web-api asp.net-web-api2

javascript - net - WebApi 2 POST con un solo parámetro de cadena que no funciona



web api rest c# tutorial (3)

Tengo el siguiente controlador:

public class ValuesController : ApiController { // POST api/values public IHttpActionResult Post(string filterName) { return new JsonResult<string>(filterName, new JsonSerializerSettings(), Encoding.UTF8, this); } }

Configuracion webpi

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

Yo uso este código js para llamar a la 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); } });

Obtengo un método 405 no permitido (post)

¿Algunas ideas?


Agregue [FromBody] a la firma del método API como public IHttpActionResult Post([FromBody]string filterName) y envuelva el parámetro de datos ajax con comillas: data: ''"'' + bodyContent + ''"'' .

No muy intuitivo, pero funciona.


Agregue el atributo [HttpPost] al método en el controlador


do#

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); } });

Explicación

Debido a que solo está enviando un solo valor, agregue el signo = delante de él para que se trate como codificación de formularios. También puede agregar el tipo de contenido si desea dejar en claro que esto es lo que está haciendo con la llamada ajax.

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

Alternativamente, también puede enviar el contenido a través de la URL O envolver el contenido en un objeto en el servidor, así como en la llamada ajax y estratificarlo.

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); } });