如何在发布数据后阅读WebClient响应? WebClient.UploadData方法(String,String,Byte [])

时间:2017-08-30 07:58:08

标签: c# asp.net api c#-4.0 asp.net-web-api

我的代码在这里。

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项目中创建get方法。

[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输出?

1 个答案:

答案 0 :(得分:0)

在WebApi中发送数据的优选方法是使用JSON。但是如果你想使用表格编码数据,你应该:

  1. 提示WebAPI使用请求体读取参数并使用简单类型 public HttpResponseMessage doc2pdf([FromBody]string fileContent)
  2. 使用前导“=”符号发送数据。
  3. 所以,客户端代码

    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
    }