带参数的webapi post方法不起作用

时间:2022-03-12 13:08:28

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.

当我调用包含带NO参数的post方法的webAPI控制器时,它会转到该方法。但是,当我传递参数(以及当我使用参数更新api控制器)时,请参阅第1个片段下方的片段,我得到405错误,它不支持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:

更新 - 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?

是因为我没有解决方案并且回答params(在我的WebApiConfig中)它不识别它们?

What am I doing incorrectly?

我做错了什么?

7 个解决方案

#1


6  

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...

这是设置路线的略有不同的方法,但我更喜欢它。在您的控制器代码中为每个代表GET请求POST的方法添加路由前缀和路由...

[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.

当我设置我的WebAPI时,这对我有用。如果有人发现任何错误的解释,请告诉我。我还在学习(而且永远都是),但只是想让你知道我做了哪些工作。

#2


4  

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

#3


3  

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

添加另一个MapHttpRoute,它将接受'solution'和'answer'作为参数

sample :

样品:

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

#4


2  

[HttpPost]

public bool Post(Captcha cap)
{
    return _service.Post();
}

And

Change data: JSON.stringify(jsondata) to data : jsondata .

将数据:JSON.stringify(jsondata)更改为数据:jsondata。

#5


1  

The Reason it doesn't work is because there is not route that will accept 2 parameter at your [post] address - api/captcha/.

它不起作用的原因是因为没有路由会在[post]地址接受2参数 - api / captcha /。

you have 2 options, either set up attribute routing in controller as

你有2个选项,或者在控制器中设置属性路由

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

}

or create a model as

或者创建一个模型

Public class CaptchaModel
{
   Public string Solution {get; set;}
   Public string Answer {get; set;}
}

And in your action method

并在你的行动方法

[HttpPost]
public bool Post([FromBody] CaptchaModel model)
{
  var solution = model.solution;
  var answer = model.answer;
  .........
  return _service.Post();
}

#6


1  

According to www.asp.net,

根据www.asp.net,

"when an HTTP method is configured for use on the server, but it has been disabled for a given URI, the server will respond with an HTTP 405 Method Not Allowed error."

“当HTTP方法配置为在服务器上使用,但已针对给定URI禁用时,服务器将响应HTTP 405 Method Not Allowed错误。”

Further reference on 405

进一步参考405

http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

#7


1  

You must remove JSON.stringify(data) from your request and then add [FromBody] in front your model. Then it will work.

您必须从请求中删除JSON.stringify(data),然后在模型前添加[FromBody]。然后它会工作。

#1


6  

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...

这是设置路线的略有不同的方法,但我更喜欢它。在您的控制器代码中为每个代表GET请求POST的方法添加路由前缀和路由...

[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.

当我设置我的WebAPI时,这对我有用。如果有人发现任何错误的解释,请告诉我。我还在学习(而且永远都是),但只是想让你知道我做了哪些工作。

#2


4  

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

#3


3  

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

添加另一个MapHttpRoute,它将接受'solution'和'answer'作为参数

sample :

样品:

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

#4


2  

[HttpPost]

public bool Post(Captcha cap)
{
    return _service.Post();
}

And

Change data: JSON.stringify(jsondata) to data : jsondata .

将数据:JSON.stringify(jsondata)更改为数据:jsondata。

#5


1  

The Reason it doesn't work is because there is not route that will accept 2 parameter at your [post] address - api/captcha/.

它不起作用的原因是因为没有路由会在[post]地址接受2参数 - api / captcha /。

you have 2 options, either set up attribute routing in controller as

你有2个选项,或者在控制器中设置属性路由

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

}

or create a model as

或者创建一个模型

Public class CaptchaModel
{
   Public string Solution {get; set;}
   Public string Answer {get; set;}
}

And in your action method

并在你的行动方法

[HttpPost]
public bool Post([FromBody] CaptchaModel model)
{
  var solution = model.solution;
  var answer = model.answer;
  .........
  return _service.Post();
}

#6


1  

According to www.asp.net,

根据www.asp.net,

"when an HTTP method is configured for use on the server, but it has been disabled for a given URI, the server will respond with an HTTP 405 Method Not Allowed error."

“当HTTP方法配置为在服务器上使用,但已针对给定URI禁用时,服务器将响应HTTP 405 Method Not Allowed错误。”

Further reference on 405

进一步参考405

http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

http://www.asp.net/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

#7


1  

You must remove JSON.stringify(data) from your request and then add [FromBody] in front your model. Then it will work.

您必须从请求中删除JSON.stringify(data),然后在模型前添加[FromBody]。然后它会工作。