简体   繁体   English

Web API [FromBody] 字符串参数总是 null

[英]Web API [FromBody] string parameter always null

I've been trying to pass string data using [FromBody] but it is always null.我一直在尝试使用[FromBody]传递字符串数据,但它始终是 null。

在此处输入图像描述

public HttpResponseMessage Post(int id, [FromBody] string value)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Success");
}

在此处输入图像描述

In ASP.NET Core you cannot simply use Model binding to get the whole JSON body text as string.在 ASP.NET Core 中,您不能简单地使用 Model 绑定来获取整个 JSON 正文作为字符串。 You have to either create a binding model or read the request body manually:您必须创建绑定 model或手动读取请求正文:

var bodyText = await this.Request.Content.ReadAsStringAsync();
[HttpPost]
public HttpResponseMessage Post(int id, [FromBody] string value)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Success");
}

The [HttpPost] attribute tells the routing engine to send any POST requests to that action method to the one method over the other. [HttpPost] 属性告诉路由引擎将发送到该操作方法的任何 POST 请求发送到一个方法而不是另一个方法。 This is a type of overloading.这是一种重载。 enter link description here 在此处输入链接描述

you can use like below;你可以像下面这样使用;

        var json = JsonConvert.SerializeObject("your value parameter value");
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        using (var client = new HttpClient())
        {
            try
            {
                client.BaseAddress = new Uri("your url" + "?id=your ID");
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authString);

                HttpResponseMessage Res = client.PostAsync("", content).Result;

                var jsonContent = Res.Content.ReadAsStringAsync().Result;
              
            }
            catch (Exception ex)
            {
                throw;
            }
        }

above codes work in my app.以上代码在我的应用程序中有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM