【问题标题】:How to implement POST and upload files in ASP C# using API?如何使用 API 在 ASP C# 中实现 POST 和上传文件?
【发布时间】:2019-10-14 18:58:59
【问题描述】:

我正在尝试使用我提供的 API 通过 ASP C# 实现 post HTTP 调用。 API 不是我制作的,但在 Postman 中可以正常工作。

这是在 Postman 中完美运行的屏幕截图:

现在,我只需要将其转换为 ASP C#,我花了几天时间谷歌搜索但未能找到我需要的答案,或者我只是找不到正确的关键字。这是我尝试过的,但它是来自公司的代码,恰好在他的页面上工作,但在我的页面上却没有(顺便说一句,他走了)。

public static objWebService PostSomething(string xml, Object md)
    {
        objWebService _webService = new objWebService();
        _webService.result = false;
        DataSet ds = new DataSet();

        XmlDocument xdoc = new XmlDocument(); //seems not used
        string responseString = string.Empty;

        string endpoint = "http://xxxxxxxxxxxxx"; // my post api.

        try
        {

            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            wrWebRequest.Headers["Authorization"] = "Basic xxxxxxxxxxxxx";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            byte[] newLine = Encoding.UTF8.GetBytes("\r\n");
            byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

            wrWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            wrWebRequest.Method = "POST";
            wrWebRequest.KeepAlive = true;

            Stream requestStream = wrWebRequest.GetRequestStream();

            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"proposal.xml\"\r\nContent-Type: application/xml;\r\n\r\n{1}", "xml", req));
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formItemBytes, 0, formItemBytes.Length);

            if (Utilities.IsFileExist(md.file1_path))
            {
                requestStream.Write(newLine, 0, newLine.Length);
                int bytesRead = 0;
                byte[] buffer = new byte[2048];
                byte[] formFileBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg;\r\n\r\n", "files", md.file1_name));
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Write(formFileBytes, 0, formFileBytes.Length);

                using (FileStream fileStream = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(md.file1_path), FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    fileStream.Close();
                }
            }

            requestStream.Write(newLine, 0, newLine.Length);
            requestStream.Write(trailer, 0, trailer.Length);
            requestStream.Close();

            HttpWebResponse wrWebResponse = wrWebRequest.GetResponse() as HttpWebResponse;

            using (Stream s = wrWebResponse.GetResponseStream())
            {
                ds.ReadXml(s);
            }

            if (ds.Tables["returnObj"] != null)
            {
                _webService.result = true;
                _webService.output = ds;
            }
            else
            {
                _webService.result = false;
            }
        }
        catch (WebException wExp)
        {
            _webService.result = false;
        }
        catch (Exception exp)
        {
            _webService.result = false;
        }
        return _webService;
    }

这是我从前同事那里得到的复制粘贴代码,我会在我认为可以安全修剪的地方进行修剪。如果还是乱七八糟,请见谅。

每当这部分代码运行时,我都会遇到这些异常。

Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.ArgumentException' in System.Web.dll

如果之前有人问过并解决了,谁能告诉我应该怎么做或将我链接到答案?

【问题讨论】:

    标签: c# asp.net http post upload


    【解决方案1】:

    好尴尬。问题是文件路径的格式错误,甚至在我的代码预览中都不可用。 (~/xxx/xx.jpg)

    【讨论】:

      【解决方案2】:

      将您的文件转换为字节[] 然后,将 byte[] 转换为 HttpContent

      HttpContent bytesContent = new ByteArrayContent(bArr);
      

      然后,然后通过

      using (var formDataImage = new MultipartFormDataContent())
      {                                                                                                                        
        formDataImage.Add(bytesContent, "image", "image");
        using (var httpImage = new HttpClient())
        {
           ServicePointManager.Expect100Continue = true;                                                                
           ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;                                                              
           httpImage.DefaultRequestHeaders.Add("Authorization", oAuthHeaderImage);                                                                
           var httpRespImage = httpImage.PostAsync(baseUrlImage, formDataImage);                                                                
           var respBodyImage = httpRespImage.Result;                                                                
           if (respBodyImage.StatusCode.ToString().ToLower() != "created")
           {
               string rspImage = httpRespImage.Exception.InnerException.ToString();                                                                    
           }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        • 2014-05-18
        • 2013-09-15
        • 1970-01-01
        • 2013-08-04
        相关资源
        最近更新 更多