0

我目前正在开发一个 MediaTypeFormatter 来处理来自 Web Api 控制器的 csv 文件。如何添加 contentHeaders.Add("content-disposition", "attachment; filename=filename.csv");

截至目前,我有以下代码,但内容处置标头被忽略。我想提供一个链接,以便为用户提供保存拨号。例如。/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;
    }

}
4

1 回答 1

1

您目前拥有的内容来不及修改标头(先发送标头,然后发送正文)。您可以覆盖调用的方法SetDefaultContentHeaders来修改传出标头。

于 2013-11-04T23:28:55.723 回答