2017-09-27 41 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

相關問題