简体   繁体   中英

Changing response content type in asp.net Web API

I have an asp.net Web Api controller with an Upload action. 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.

The problem is when I use this in IE 9, the browser doesn't accept application/json as a media type. So, I'll have to make sure the server returns plain/text . How can I do that without changing the return type of the action to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM