How do we 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");
    } 

Could you please suggest same implementation in WebAPI.

Thanks, Bhagat

Answers


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;
}

Good luck - there's lots of ways of handling files and file returns, so I want to assume you don't have some special return value on your handling.


Need Your Help

Unexpected Interpolation when using LinearSegmentedColormap

python matplotlib color-mapping

I am trying to create a custom color map which combines interpolated and discretized color segments. I am hoping that matplotlib's LinearSegmentedColormap can provide such functionality. My test ca...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.