我有一个服务器方法,它接受并编码一个字符串列表,因为IE9不读取json格式,我想要的是在http响应消息的内容中设置字符串。我似乎做得很好但是当我得到响应时,我可以在身体上找到响应,我能看到的只是我在响应消息中设置的长度。
这是代码:
public HttpResponseMessage Upload()
{
HttpResponseMessage m = new HttpResponseMessage(HttpStatusCode.OK);
List<string> returnlist = new List<string>();
for (int i = 0; i < Request.Files.Count; i++)
{
//string treatment
}
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent(string.Join(",", returnlist));
return response;
}
这是字符串包含“file1,file2,file3”的内容 但我无法在visual studio或firebug中找到它进行调试
我得到的回应是:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}
如何设置然后获取响应消息?
如果需要,这里的js是:
self.uploadfiles = function () {
//startSpinner();
if (!self.isOldIE()) {
var loc = window.location;
base_url = loc.protocol + "//" + loc.host;
baseUrl = base_url + "/";
var save = true;
var xhr = new XMLHttpRequest();
xhr.open('POST', baseUrl + 'Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function (data) {
//The responseText is the same as above
if (xhr.responseText.length > 0) {
//do stuff
}
};
答案 0 :(得分:0)
尝试使用Javascript获取响应:
var xhr = new XMLHttpRequest();
xhr.open('POST', baseUrl + 'Home/Upload', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
} else {
// do something about the error
}
};
xhr.send(formdata);
注意 open()方法的第三个布尔参数,用于异步获取。
答案 1 :(得分:0)
试试此代码
var response = Request.CreateResponse(HttpStatusCode.OK, string.Join(",", returnlist));
return response;
答案 2 :(得分:0)
由于某种原因,浏览器不显示http响应的整个主体。所以我的解决方案是编写响应的头部并从js获取头部。 也许有人知道为什么浏览器没有显示正文,或者有更好的解决方案。
这是我的控制者:
public HttpResponseMessage Upload()
{
HttpResponseMessage m = new HttpResponseMessage(HttpStatusCode.OK);
List<string> returnlist = new List<string>();
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
if (file.FileName != "")
{
string fileName = string.Format("{0}.{1}", Guid.NewGuid().ToString(), file.FileName.ToString().Split('.')[1].ToString());
returnlist.Add(fileName);
}
}
//Here I write the response message headers
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent(string.Join(",", returnlist), Encoding.UTF8, "text/html");
response.Headers.Add("data", string.Join(",", returnlist));
return response;
}
以下是我如何得到标题回复:
var xhr = new XMLHttpRequest();
xhr.open('POST', baseUrl + 'Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function (data) {
if (xhr.responseText.length > 0) {
//header response
var response = xhr.responseText;
}