Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webapi post method with parameters doesn't work

When I call my webAPI controller that contains a post method with NO parameters it goes to the method. However, when I pass parameters (and when I update the api controller with paramters as well) into this see the snippet below the 1st snippet I get the 405 error that it doesn't support POST.

var captchURL = "/api/Captcha";  
$.ajax({
       url: captchURL,
       dataType: 'json',
       contentType: 'application/json',
       type: 'POST'
})



var jsondata = {solution: "7", answer: "7"};
    var captchURL = "/api/Captcha";  
    $.ajax({
           url: captchURL,
           dataType: 'json',
           contentType: 'application/json',
           type: 'POST',
           data: JSON.stringify(jsondata)
    })

UPDATE - Controller Code:

public class CaptchaController : ApiController
{
    private readonly ICaptchaService _service;
    public CaptchaController(ICaptchaService service)
    {
        _service = service;
    }

    public Captcha Get()
    {
        return _service.Get();
    }

    [HttpPost]
    public bool Post(string solution, string answer)
    {
        return _service.Post();

    }
}

UPDATE - WebApiConfig:

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

Is it because I don't have the solution and answer params (in my WebApiConfig) that it doesn't recognize them?

What am I doing incorrectly?

like image 595
webdad3 Avatar asked Dec 23 '15 22:12

webdad3


People also ask

How do I call a post method with multiple parameters?

$(document). ready(function () { var data = {name: "", tag: ""}; var url = '/api/list/Post'; $. ajax({ url: url, data: JSON. stringify(data), type: 'POST', contentType: "application/json", }); });

How do I pass multiple parameters to Web API controller methods?

You can pass parameters to Web API controller methods using either the [FromBody] or the [FromUri] attributes. Note that the [FromBody] attribute can be used only once in the parameter list of a method.

How do I pass body parameters in Web API?

Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.

Why your FromBody parameter is always null?

If you need to get multiple values from the request body, define a complex type. But still the value of email is NULL . The JavaScript code is part of generic method we use, so that's why the content-type is set to application/json; charset=utf-8 .


3 Answers

This is a slightly different method of setting the route, but I prefer it. In your controller code add a route prefix and routes for each method that will represent a POST of GET request...

[RoutPrefix("Captcha")]
public class CaptchaController : ApiController
{

    [Route("Post/{solution}/{answer}")]
    [HttpPost]
    public bool Post(string solution, string answer)
    {
        return _service.Post();

    }
}

This should work as long as you are setting the path correctly, using the correctly typed parameters, and returning a correctly typed value. If you use a Model then you do not have to add the parameters into the Route path.

This worked for me when I was setting up my WebAPI. If anyone sees anything wrong with explanation please let me know. I am still learning (and always will be), but just wanted to let you know what I did that worked.

like image 159
M. Carlson Avatar answered Oct 09 '22 05:10

M. Carlson


create a model

public class Captcha {
    public string solution { get; set; }
    public string answer { get; set; }
}

the controller is this

[HttpPost]
public string Post([FromBody] Captcha cap)
{
    return cap.solution + " - " + cap.answer;
}
like image 40
Mauro Sala Avatar answered Oct 09 '22 06:10

Mauro Sala


Add another MapHttpRoute which will accept 'solution' and 'answer' as parameters

sample :

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{solution}/{answer}",
            defaults: new { solution = RouteParameter.Optional, answer= RouteParameter.Optional }
        );
like image 23
Umesh Kadam Avatar answered Oct 09 '22 05:10

Umesh Kadam