在 API 方法中使用 [FromBody] 注释时获取 404 错误请求

Getting 404 Bad Request when using [FromBody] annotation in API method

我正在尝试在 MVC 和 .NET Core API 之间发送一些基本 POST 数据。 当我 post 数据时,我得到这个错误:

The remote server returned an error: (400) Bad Request

我的控制器:

[HttpPost]
[Route ("simple")]
public int PostSimple([FromBody] string value)
{
    return 0;
}

我给这个控制器的 POST 代码:

string url = "my.api/Controller/Simple";
var client = new WebClient();
client.Headers.Add("Content-Type:application/json");

string data = "some data I want to post";
byte[] postArray = Encoding.ASCII.GetBytes(data);

var response = client.UploadData(encoded, "POST", postArray);

只有当我使用 [FromBody] 时才会发生这种情况 当我删除它时,我可以访问 web 方法,但是我看不到 POSTed 数据。

如有任何想法,我们将不胜感激。

您的变量“数据”应包含一个 JSON 字符串。

var response = client.UploadData(url, "POST", postArray);

您收到此错误是因为您实际上发送了无效数据。服务器期望的(来自正文)是这样的:

{
  "value" : "some data I want to post"
}

你发送的只是一个字符串,没有别的;这将导致无效请求。 在您的 POST 代码中将您的方法更改为如下内容 (pseudo-coded):

var stringedClass = new MyClass() { value = "This is the string" };
var message = new HttpRequestMessage(HttpMethod.Post, "url");
message.Content = new StringContent(JsonConvert.SerializeObject(stringedClass), Encoding.UTF8, "application/json");
using (var response = await _client.SendAsync(msg).ConfigureAwait(false))
        {
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(response.ToString());
            }
        }

您明确告诉您的 api 控制器除了 json 格式 (header : Content-Type:application/json)。然后,您必须提供符合规则的 body。

原始字符串不是 json,这就是为什么你要返回这个 400 错误请求。

为了解决这个问题,您首先需要创建一个 class 来映射请求 json

public class MyRequest
{
    public string Value { get; set; }
}

然后在你的控制器中使用它

[HttpPost]
[Route ("simple")]
public int PostSimple([FromBody] MyRequest request)
{
    // access the value using request.Value
}

最后,给你的控制器发送一个jsonbody

string data = "{\"value\" : \"some data I want to post\"}";
byte[] postArray = Encoding.ASCII.GetBytes(data);

var response = client.UploadData(encoded, "POST", postArray);