Omar Olivo
Omar Olivo

Reputation: 45

How to override response headers in ASP.NET Web Api using MediaTypeFormatter

I'm currently developing a MediaTypeFormatter to process a csv files from a Web Api Controller. How can I add the contentHeaders.Add("content-disposition", "attachment; filename=filename.csv");

As of now, I have the following code, but the content-disposition header is ignored. I would like provide a link such that presents the user with the save dialod. eg. /api/students?format=csv

public class ServiceStackCSVFormatter : MediaTypeFormatter
{

    public ServiceStackCSVFormatter()
    {            
        //this.AddQueryStringMapping("format","csv", "text/csv");
        this.AddQueryStringMapping("format", "csv", "text/html"); 
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));         
    }

    public override bool CanWriteType(Type type)
    {
        if (type == null)
            throw new ArgumentNullException("type");

        return true;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        content.Headers.Clear();
        content.Headers.Add("content-disposition", "attachment; filename=result.csv");          
        var task = Task.Factory.StartNew(() => CsvSerializer.SerializeToStream(value, writeStream));
        return task;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
    { 
        var task = Task<object>.Factory.StartNew(() => CsvSerializer.DeserializeFromStream(type, readStream));
        return task;
    }
    public override bool CanReadType(Type type)
    {
        return true;
    }

}

Upvotes: 0

Views: 981

Answers (1)

Kiran
Kiran

Reputation: 57989

What you currently have is too late to modify the headers (headers are sent first and then the body). You can override the method called SetDefaultContentHeaders to modify the outgoing headers.

Upvotes: 1

Related Questions