如何使用API​​在ASP C#中实现POST和上传文件?

时间:2019-05-29 08:12:13

标签: c# asp.net http post upload

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

以下是在邮递员中完美运行的屏幕截图:

enter image description here

enter image description here

现在,我只需要将其转换为花了几天时间但仍无法找到所需答案的ASP C#,否则我就找不到合适的关键字。这是我尝试过的方法,但这是该公司的代码,恰好可以在他的页面上工作,而不能在我的页面上工作(他已经离开了BTW)。

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

任何人都可以告诉我该怎么做,或者将我链接到答案(如果之前曾被问及解决过吗?)?

2 个答案:

答案 0 :(得分:0)

将文件转换为字节[] 然后将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();                                                                    
     }
  }
}

答案 1 :(得分:0)

多么尴尬。问题是文件路径格式错误,这在我的代码预览中什至不可用。 (〜/ xxx / xx.jpg)