在ASP.NET Web API中,可以使用模型绑定来映射application/x-www-form-urlencoded格式的HTTP POST请求。下面是一个示例解决方法:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public IHttpActionResult Post([FromBody]Person person)
{
// 处理接收到的数据
// 返回响应
}
config.Formatters.Add(new FormUrlEncodedMediaTypeFormatter());
using (var client = new HttpClient())
{
var parameters = new Dictionary
{
{ "Id", "1" },
{ "Name", "John Doe" }
};
var encodedContent = new FormUrlEncodedContent(parameters);
var response = await client.PostAsync("api/person", encodedContent);
// 处理响应
}
在上面的示例中,我们使用了HttpClient类来发送HTTP POST请求,并将数据编码为application/x-www-form-urlencoded格式。在服务器端,模型绑定将自动将请求体中的数据映射到Person模型对象中,然后可以在POST方法中进行处理。