简体   繁体   English

在ASP.NET Web API中更改响应内容类型

[英]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.

相关问题 ASP.NET Web API无法序列化响应内容 - ASP.NET Web API failed to serialize the response content ASP.NET Web API用户选择的内容类型 - asp.net web api user selected content type ASP.NET Web API中的内容协商 - Content Negotiation in ASP.NET Web API 使用OData QueryableAttribute修改从ASP.NET Web API返回的响应内容 - Modifying response content returned from ASP.NET Web API using OData QueryableAttribute ASP.Net Web APi C#-GetAsync不返回XML响应内容 - ASP.Net Web APi C# - GetAsync not returning XML response content 如何将API响应“内容类型为jpeg的文件流”转换为ASP.NET中的图像文件 - How to convert API response “File Stream with content type jpeg” to image file in ASP.NET 如何在ASP.NET Web Api中使用text / xml媒体类型进行响应 - How to response with text/xml media type in ASP.NET Web Api 更改ASP.NET Web API的媒体类型Formatter上的响应标头 - Change Response Headers on Media Type Formatter for ASP.NET Web API asp.net Web API 2.1在控制器中使用内容类型应用程序xml获取空对象 - asp.net web api 2.1 getting null object in controller with content type application xml 无法让 ASP.NET web api 使用未指定的内容类型 - Unable to get ASP.NET web api to consume an unspecified content type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM