发布请求上传PDF文件C#

时间:2019-06-07 15:06:47

标签: c# pdf post upload request

我正在发送带有pdf文件附件example.pdf的后期请求-此文件已作为“内容”添加到Visual Studio中的项目。问题是我收到400错误的请求。 API服务器正在接收(IFormFile uploadFile),但是在我的情况下,uploadFile为null。 授权好,URL,标题也。我通过邮递员检查了它,它工作正常。 调试模式下的requestbody为'{byte [63933]}' 如何在C#中解决这个问题?

string pathToPdfFile = "Scenarios\DefaultScenario\example.pdf";
byte[] requestBody = File.ReadAllBytes(pathToPdfFile);     

public static string PostRequestUploadFile(string url, Dictionary<string, string> headersDictionary, byte[] requestbody)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            if (headersDictionary != null)
            {
                foreach (KeyValuePair<string, string> entry in headersDictionary)
                {
                    request.Headers.Add(entry.Key, entry.Value);
                }
            }
            request.ContentType = "application/pdf";
            Stream dataStream = request.GetRequestStream();
            byte[] byteArray = requestbody;
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception Ex)
            {
                return Ex.ToString();
            }
        }

1 个答案:

答案 0 :(得分:0)

我做了一些更改 我添加了Content Length标头

您可能必须将application/pdf更改为application/x-www-form-urlencoded 最后,我不知道您要在headersDictionary中发送哪些参数,但可能缺少“文件”字段名称的形式

var request = (HttpWebRequest)WebRequest.Create(url);

request.Method = "POST"; // Consider using WebRequestMethods.Http.Post instead of "POST"
if (headersDictionary != null){
    foreach (KeyValuePair<string, string> entry in headersDictionary){
        request.Headers.Add(entry.Key, entry.Value);
    }
}

request.ContentType = "application/pdf";
// Dependending on your server, you may have to change
// to request.ContentType = "application/x-www-form-urlencoded";

byte[] byteArray = requestbody; // I don't know why you create a new variable here
request.ContentLength = byteArray.Length;

using (var dataStream = request.GetRequestStream()){
    dataStream.Write(byteArray, 0, byteArray.Length);
}

using(var response = (HttpWebResponse)request.GetResponse()){
    using(var reader  = new StreamReader(response.GetResponseStream())){
        return reader.ReadToEnd();
    }
}

在使用this的测试中,我必须使用request.ContentType = "application/x-www-form-urlencoded"而不是PDF(我无法模拟整个设置)

由于我没有服务器,您正在尝试发送该服务器,并且没有参数,因此无法在您的环境中对此进行测试

供以后参考,HttpWebRequest是应避免使用的旧版(过时)实现,新实现应使用HttpClient read more