[英]Changing response content type in asp.net Web API
I have an asp.net Web Api controller with an Upload action. 我有一个具有Upload操作的asp.net Web Api控制器。 Here's the simplified version of the Upload action: 这是上载操作的简化版本:
[HttpPost]
public async Task<string> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var file = provider.Contents[0];
try
{
// Save the file...
}
catch (Exception e)
{
return JsonConvert.SerializeObject(new
{
status = "error",
message = e.Message
});
}
return JsonConvert.SerializeObject(new
{
status = "success"
});
}
The return type of the action has to be string, because it's used by a third-party upload widget that accepts serialized JSON only. 该操作的返回类型必须为字符串,因为第三方上传小部件使用了该操作,该小部件仅接受序列化的JSON。
The problem is when I use this in IE 9, the browser doesn't accept application/json
as a media type. 问题是当我在IE 9中使用此功能时,浏览器不接受application/json
作为媒体类型。 So, I'll have to make sure the server returns plain/text
. 因此,我必须确保服务器返回plain/text
。 How can I do that without changing the return type of the action to HttpResponseMessage
? 如何在不将操作的返回类型更改为HttpResponseMessage
下执行此操作?
You can do something like this: 您可以执行以下操作:
public async Task<JsonResult> Upload()
return Json(someData, "text/html");
Although another option to just return the json is post though an iFrame then it will not attempt to download the returning html. 尽管仅返回json的另一个选项是通过iFrame发布,但它不会尝试下载返回的html。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.