2017-09-27 40 views
1

我的控制器无法通过POST方法接受字符串。什么可能是错的?当我创建HttpClient像这样发送内容:通过POST发送字符串 - 不支持的媒体类型或空参数

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) 
{  
} 
+0

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

回答

3

端点最有可能配置为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

相关问题