0

我目前正在開發一個MediaTypeFormatter來處理來自Web Api控制器的csv文件。如何添加 contentHeaders.Add(「content-disposition」,「attachment; filename = filename.csv」);如何使用MediaTypeFormatter覆蓋ASP.NET Web Api中的響應頭

截至目前,我有以下代碼,但內容處置標題被忽略。我想提供一個鏈接,向用戶顯示save dialod。例如。/api/students?格式= 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; 
    } 

} 

回答

1

你目前有什麼已經太晚了,無法修改標題(標題首先發送,然後發送正文)。您可以覆蓋名爲SetDefaultContentHeaders的方法來修改傳出標題。

+0

謝謝!有效! –

相關問題