【发布时间】:2017-11-15 09:57:47
【问题描述】:
我正在开发 ASP.Net 项目。我必须在 HP QC ALM 12.5x 中上传缺陷的附件。
身份验证部分已经完成并成功运行。
上传缺陷到附件时,收到WebException was unhandled: The remote server returned an error: (415) Unsupported Media Type.
我已经写了下面的代码
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HPALMUrl + "/rest/domains/" + HPALMDomain + "/projects/" + HPALMProject + "/attachments");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en-US");
request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch");
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)";
request.ContentType = "Content-Type: multipart/form-data; boundary=" + boundary;
request.AllowWriteStreamBuffering = false;
request.ContentLength = imageBytes.Length;
authRequest.KeepAlive = true;
request.CookieContainer = createSessionRequest.CookieContainer; //successfully authenticated cookie
string contentDisposition = "form-data; entity.type=\"{0}\"; entity.id=\"{1}\"; filename=\"{2}\"; Content-Type=\"{3}\"";
request.Headers.Add("Content-Disposition", string.Format(contentDisposition, "defect", "4", "Defect Attachment.png", "application/octet-stream")); //I am not clear with passing content disposition. Please let me know if this should be modified.
我正在尝试上传如下图片文件
string path = @"C:\TestAttachment.png";
byte[] imageBytes = System.IO.File.ReadAllBytes(path);
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
using (MemoryStream memoryStream = new MemoryStream(imageBytes))
{
byte[] buffer = new byte[imageBytes.Length];
int bytesRead = 0;
while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
}
var response = (HttpWebResponse)request.GetResponse(); //Receiving Error here
string responseText = string.Empty;
if (response.StatusCode == HttpStatusCode.OK)
responseText = "Update completed";
else
responseText = "Error in update";
请让我知道我做错了什么。
我也不确定是否通过rest api 中提到的内容处置。
提前致谢!
【问题讨论】:
-
Content-Disposition是一个 response 标头。 服务器 将在其响应中设置它。根本不要在请求中设置它 -
至于错误本身,附件是文件,而您的
Content-type是multipart/form-data。您没有发布表格。您正在创建一个新文件。也许您应该检查一下 HTTP 的一般工作原理和 REST 的具体工作原理? -
@PanagiotisKanavos 但是,在 API reference 中,标题部分提到了 Content-Disposition
-
在哪里?如果你搜索它,你不会找到那个词
-
我找到了。它根本不是 REST API,只是表单发布。
标签: c# asp.net rest hp-quality-center