首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在发布数据后读取WebClient响应?WebClient.UploadData方法(String, String, Byte[])

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

Stack Overflow用户
提问于 2017-08-30 07:58:08
回答 1查看 5.9K关注 0票数 2

我的密码在这里。

代码语言:javascript
复制
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项目中创建的方法,如下所示。

代码语言:javascript
复制
[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 {字节}。

现在,如何读取HTTP输出?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-30 17:37:11

在WebApi中发送数据的更好方法是使用JSON。但是,如果要使用表单编码的数据,则应:

  1. 提示WebAPI使用请求体读取参数并使用简单类型public HttpResponseMessage doc2pdf([FromBody]string fileContent)
  2. 发送带有前导"=“符号的数据。

所以,客户端代码

代码语言:javascript
复制
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);

服务器端代码

代码语言:javascript
复制
public HttpResponseMessage doc2pdf([FromBody]string fileContent)
{
    //..logic here
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45954972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档