2017-08-30 47 views
1

我的代碼在這裏。如何在發佈數據後讀取WebClient響應? WebClient.UploadData方法(字符串,字符串,字節[])

string uriString = "http://www.Testcom"; 
WebClient myWebClient = new WebClient(); 
string postData = "data"; 
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded"); 
Console.WriteLine(myWebClient.Headers.ToString()); 
byte[] byteArray = Encoding.ASCII.GetBytes(postData);   
byte[] responseArray = myWebClient.UploadData(new 
Uri(uriString),"POST",byteArray); 

現在我調用UploadData並在我的API項目中創建類似這樣的方法。

[HttpPost] 
[Route("doc2pdf")] 
public HttpResponseMessage doc2pdf(byte[] fileContent) 
{ 
    string pdfContent = string.Empty; 
    //if(string.IsNullOrEmpty(docContent)) 
    //{ 
    // var resp = Request.CreateResponse(HttpStatusCode.BadRequest,"Document content is empty."); 
    // return resp; 
    //} 
    if(fileContent != null || fileContent.Length > 0) 
    { 
     ..logic here 
    } 
} 

問題始終是fileContent get {byte [0]}。 enter image description here

現在,我該如何讀取HTTP輸出?

回答

0

在WebApi中發送數據的最佳方式是使用JSON。但是如果你想使用的形式編碼的數據,你應該:

  1. 提示的WebAPI使用請求體讀取參數和使用簡單的類型 public HttpResponseMessage doc2pdf([FromBody]string fileContent)
  2. 與一家領先的「=」號發送數據。

因此,客戶端代碼

string uriString = "http://www.Testcom"; 

WebClient myWebClient = new WebClient(); 
string postData = "=data"; 
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 
Console.WriteLine(myWebClient.Headers.ToString()); 
byte[] byteArray = Encoding.ASCII.GetBytes(postData); 
byte[] responseArray = myWebClient.UploadData(new Uri(uriString), "POST", byteArray); 

服務器端代碼

public HttpResponseMessage doc2pdf([FromBody]string fileContent) 
{ 
    //..logic here 
}