【问题标题】:Sending string via POST - unsupported media type or null parameter通过 POST 发送字符串 - 不支持的媒体类型或空参数
【发布时间】:2017-09-27 14:28:18
【问题描述】:

我的控制器无法通过POST 方法接受字符串。有什么问题?当我创建HttpClient 并发送这样的内容时:

var content = new FormUrlEncodedContent(new []
{
     new KeyValuePair<string, string>("signature", "someexamplecontent"), 
});

var response = await _client.PostAsync(path, content);

我收到一个错误:415, Unsupported media type,它没有进入控制器。相反,当我使用PostAsJsonAsync - 进入但参数signature 为空。

var response = await _client.PostAsJsonAsync(path, content);

这是控制器中的一个方法:

[HttpPost("generatecert")]
public byte[] PostGenerateCertificate([FromBody] string signature)
{      
}

【问题讨论】:

  • 您是否检查过请求是否发送了正确的Content-TypeContent-Encoding 标头,并确保服务器接受“application/x-www-form-urlencoded”内容类型?这是您接收 POST 数据的唯一操作吗?

标签: c# asp.net-mvc asp.net-web-api dotnet-httpclient


【解决方案1】:

端点很可能是为 JSON 内容配置的。如果使用PostAsJsonAsync,则只需传递要发布的字符串。

var signature = "someexamplecontent";    
var response = await _client.PostAsJsonAsync(path, signature);

该方法将序列化并为请求设置必要的内容类型标头。

如果发布更复杂的对象,例如

public class Model {
    public string signature { get; set; }
    public int id { get; set; }
}

同样适用,但需要更新操作以预期复杂对象

[HttpPost("generatecert")]
public byte[] PostGenerateCertificate([FromBody] Model signature) {
    //... 
}

客户端会发送对象

var model = new Model {
    signature = "someexamplecontent",
    id = 5
};
var response = await _client.PostAsJsonAsync(path, model);

参考Parameter Binding in ASP.NET Web API

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-23
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多