【问题标题】:How to read a WebClient response after posting data? WebClient.UploadData Method (String, String, Byte[])发布数据后如何读取 WebClient 响应? WebClient.UploadData 方法 (String, String, Byte[])
【发布时间】:2018-02-07 20:19:25
【问题描述】:

我的代码在这里。

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 获取 {byte[0]}。

现在,我如何读取 HTTP 输出?

【问题讨论】:

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


    【解决方案1】:

    在 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
    }
    

    【讨论】:

      猜你喜欢
      • 2010-11-04
      • 2015-12-10
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2019-03-07
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多