排查c# post请求返回415错误,核心是确保http请求头中的`content-type`与序列化后的请求体格式严格匹配。通常做法是使用`httpclient`配合`stringcontent`或`bytearraycontent`发送数据,并显式指定正确的媒体类型(如`application/json`),若服务器端配置了特定的模型绑定器或路由约束,还需检查服务端期望的格式是否与客户端一致。

HttpClient发送JSON时如何正确设置Content-Type
使用HttpClient发送POST请求时,必须通过StringContent构造函数明确指定编码和媒体类型,否则默认可能为text/plain导致服务端拒绝。例如,发送JSON数据时应使用new StringContent(json, Encoding.UTF8, "application/json"),这样生成的请求头会自动包含正确的Content-Type,避免415错误。

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using var client = new HttpClient();
var data = new { Name = "Test", Value = 123 };
var json = System.Text.Json.JsonSerializer.Serialize(data);
// 关键:第三个参数指定 application/json
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://api.example.com/data", content);
Console.WriteLine(response.StatusCode); // 预期 200 OK
}
}
服务端接收端点如何验证Content-Type匹配
服务端在接收到请求时,会检查Content-Type头以决定使用哪个格式化器(Formatter)或模型绑定器。如果客户端发送的是XML但头标记为JSON,或者反之,ASP.NET Core等框架会直接返回415 Unsupported Media Type。开发者应确保服务端API契约与客户端调用完全一致,包括大小写和子类型(如json vs application/vnd.api+json)。

// 服务端示例 (ASP.NET Core Controller)
[HttpPost]
[Consumes("application/json")] // 显式声明只接受 JSON
public IActionResult ReceiveData([FromBody] MyModel model)
{
if (model == null) return BadRequest();
return Ok(new { Received = true });
}
// 如果客户端发送 Content-Type: text/plain
// 即使 Body 是合法 JSON,也会触发 415 或模型绑定失败
当Content-Type包含字符集参数时是否影响解析
在Content-Type头中包含字符集参数(如application/json; charset=utf-8)通常不会影响解析,因为大多数现代Web框架会忽略参数部分仅匹配主类型。然而,某些严格的服务端实现或旧版中间件可能会因参数不匹配而拒绝请求。建议客户端发送标准格式application/json,并在服务端配置中允许常见的字符集后缀,以确保兼容性。











