Set content type in Web Api

Return the response with content-type with text/plain format

Set content-type to "text/plain" in asp.net web api

 

We are using asp.net web api in our application, in that we are trying to return the response with content-type with text/plain format but We are unable to succeeded. Same thing we tried with ASP.NET MVC it is working fine could you please provide me equivalent solution in Web API.

Please find below for the function implemented in ASP.NET MVC

    public JsonResult FileUpload(HttpPostedFileBase file)
    {
        string extension = System.IO.Path.GetExtension(file.FileName);
        string bufferData = string.Empty;

        if (file != null)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                byte[] array = ms.GetBuffer();
                var appendInfo = "data:image/" + extension + ";base64,";
                bufferData = appendInfo + Convert.ToBase64String(array);
            }

        }
        var result = new
        {
            Data = bufferData

        };

       return Json(result,"text/plain");
    } 

From StackOverflow.com:

httpresponse - How do we set content-type to "text/plain" in asp.net web api - Stack Overflow


Answer 1:
[HttpGet]
public HttpResponseMessage HelloWorld()
{
    string result = "Hello world! Time is: " + DateTime.Now;
    var resp = new HttpResponseMessage(HttpStatusCode.OK);
    resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
    return resp;
}
This works for me without using a custom formatter.

If you explicitly want to create output and override the default content negotiation based on Accept headers you won't want to use Request.

CreateResponse() because it forces the mime type.

Instead explicitly create a new HttpResponseMessage and assign the content manually.

The example above uses StringContent but there are quite a few other content classes available to return data from various .NET data types/structures.


Answer 2:

Web Api does the JSON work for you, so you can simplify your code handling on the endpoint. By default, you need to make changes in your WebApiConfig.cs for everything to work nicely. I've modified your method below:

public HttpResponseMessage FileUpload(HttpPostedFileBase file) { 
    var result = new HttpResponseMessage(HttpStatusCode.NotFound);
    var bufferData = string.Empty;

    try
    {
        if (file != null)
        {
            var extension = System.IO.Path.GetExtension(file.FileName); 
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                var array = ms.GetBuffer();
                var appendInfo = "data:image/" + extension + ";base64,";
                bufferData = appendInfo + Convert.ToBase64String(array);

                result.StatusCode = HttpStatusCode.OK;
                // Set Headers and Content here
                result.Content = bufferData;
            }

        }
    }
    catch(IOException ex)
    {
        // Handle IO Exception
    }

    return result
}
The changes you need to make in your WebApiConfig.cs could look like this:

public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}",
                defaults: null,
                constraints: new { action = @"\D+" }
                );
// This makes the response default into JSON instead of XML
        config.Formatters.Remove(config.Formatters.XmlFormatter);
            }
As a note, the very fastest fix you can make to your code would be to do this, but I don't recommend returning strings.

public string FileUpload(HttpPostedFileBase file) { 
    var result = new HttpResponseMessage(HttpStatusCode.NotFound);
    var bufferData = string.Empty;

        if (file != null)
        {
            var extension = System.IO.Path.GetExtension(file.FileName); 
            using (MemoryStream ms = new MemoryStream())
            {
                file.InputStream.CopyTo(ms);
                var array = ms.GetBuffer();
                var appendInfo = "data:image/" + extension + ";base64,";
                bufferData = appendInfo + Convert.ToBase64String(array);

                return bufferData;
            }

        }
// If you get here and have not returned, 
// something went wrong and you should return an Empty
              return String.Empty;
}