【问题标题】:WebApi HttpPost body content nullWebApi HttpPost 正文内容 null
【发布时间】:2018-04-18 10:14:52
【问题描述】:

在我的 WebApi 中,我有一个 HttpGetHttpPost 方法,get 方法工作正常,并且调用了 post 方法,但正文内容始终为空,除非在 HttpRequestMessage 中使用。我尝试以字符串格式(首选数据类型)以及模型提供正文内容,但这些方法都不起作用。我也尝试过切换内容类型但没有成功。有谁知道我是否做错了什么,或者我如何轻松地从HttpRequestMessage 获取变量数据,在下面的示例中是“测试”。

方法一:

[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem([FromBody]string filecontent, string companycode)
{
   MessageBox.Show(filecontent);

   Return Ok("");
}

方法2(带模型):

[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem([FromBody]ItemXML filecontent, string companycode)
{
   MessageBox.Show(filecontent.XMLContent);

   Return Ok("");
}

型号:

public class ItemXML
{
  public ItemXML(string content)
  {
    XMLContent = content;
  }
  public string XMLContent { get; set; }      
}

方法三:

[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem(HttpRequestMessage filecontent, string companycode)
{
   var content = filecontent.Content.ReadAsStringAsync().Result;    
   MessageBox.Show(content);

   Return Ok("");
}

方法3内容字符串(“test”是提供的值):“content”------WebKitFormBoundarydu7BJizb50runvq0\r\nContent-Disposition: form-data; name=\"filecontent\"\r\n\r\n\"test\"\r\n------WebKitFormBoundarydu7BJizb50runvq0--\r\n" string"

【问题讨论】:

  • 显示请求是如何产生的。您是在发布 JSON 还是表单数据?由于文件内容参数名称而采用形式
  • 我尝试了两种方法,但是没有成功

标签: c# asp.net-web-api swagger postman


【解决方案1】:

创建模型存储数据发送到服务器

public class Model {
    public string filecontent { get; set;}
    public string companycode { get; set;}
}

更新操作

[HttpPost]
[Route("api/v1/AddItem")]      
public IHttpActionResult AddItem([FromBody]Model model) {
    if(ModelStat.IsValid) {
        return Ok(model); //...just for testing
    }
    return BadRequest();
}

在客户端确保正确发送请求。在这种情况下将使用 JSON。

public client = new HttpClient();

var model = new {
    filecontent = "Hello World",
    companycode = "test"
};

var response = await client.PostAsJsonAsync(url, model);

如果使用其他类型的客户端,请确保发送的数据格式正确,以便 Web API 操作接受请求。

参考Parameter Binding in ASP.NET Web API

【讨论】:

  • 这成功了,你知道为什么它以前不起作用吗?是因为模型中没有包含公司代码吗?
  • @Alim 我认为这是控制器无法识别请求的组合,因为操作的定义方式和数据发送方式的格式。
  • @Alim 我包含了一个关于如何使用[FromBody]的参考链接
  • 您不必将 [FromBody] 与对象一起使用。它默认从正文获取信息,因为它不是链接中定义的“简单”类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2013-03-15
  • 2021-01-12
  • 2018-07-26
  • 1970-01-01
相关资源
最近更新 更多