C# WebApi HttpPost正文内容为空
在我的WebApi中,我有一个C# WebApi HttpPost正文内容为空,c#,asp.net-web-api,swagger,postman,C#,Asp.net Web Api,Swagger,Postman,在我的WebApi中,我有一个HttpGet和HttpPost方法,get方法工作正常,调用了post方法,但正文内容始终为空,除非在HttpRequestMessage中使用。我尝试以字符串格式(首选数据类型)和模型提供正文内容,但这两种方法都不起作用。我还尝试了切换内容类型,但没有成功。是否有人知道我是否做错了什么,或者我如何从HttpRequestMessage中轻松获取变量数据,在下面的示例中是“test” 方法1: [System.Web.Http.HttpPost] [Route("
HttpGet
和HttpPost
方法,get方法工作正常,调用了post方法,但正文内容始终为空,除非在HttpRequestMessage
中使用。我尝试以字符串格式(首选数据类型)和模型提供正文内容,但这两种方法都不起作用。我还尝试了切换内容类型,但没有成功。是否有人知道我是否做错了什么,或者我如何从HttpRequestMessage
中轻松获取变量数据,在下面的示例中是“test”
方法1:
[System.Web.Http.HttpPost]
[Route("api/v1/AddItem")]
public IHttpActionResult AddItem([FromBody]string filecontent, string companycode)
{
MessageBox.Show(filecontent);
Return Ok("");
}
方法2(带模型):
型号:
public class ItemXML
{
public ItemXML(string content)
{
XMLContent = content;
}
public string XMLContent { get; set; }
}
方法3:
[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\n内容配置:表单数据;名称=\“filecontent\”\r\n\r\n\“测试\”\r\n------WebKitFormBoundarydu7BJizb50runvq0--\r\n“字符串”创建要发送到服务器的模型存储数据
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操作接受请求
参考显示请求是如何提出的。您是否发布JSON或表单数据?由于filecontent参数名而采用表单我尝试了两种方法,但都没有成功,但是这确实奏效了,您是否知道为什么它以前不起作用?是因为模型中没有包含companycode吗?@Alim我相信这是由于控制器没有识别请求,因为动作是如何定义的,数据是如何发送的。@Alim我包含了一个关于如何使用
[FromBody]
的参考链接,您不必将[FromBody]与对象一起使用。默认情况下,它从主体获取信息,因为它不是链接中定义的“简单”类型
public client = new HttpClient();
var model = new {
filecontent = "Hello World",
companycode = "test"
};
var response = await client.PostAsJsonAsync(url, model);