0

を置き換える方法コントローラーASP.Net ApiController私はそれはASP.net MVCで書かれた、方法を持っているController.Response

[HttpGet] 
     public void ExportClientsListToCSV() 
     { 
      Response.Clear(); 
      Response.ClearHeaders(); 
      Response.ClearContent(); 
      Response.AddHeader("content-disposition", "attachment;filename=Exported_Contacts.csv"); 
      Response.ContentType = "text/csv"; 
      Response.ContentEncoding = Encoding.Unicode; 
      Response.BinaryWrite(Encoding.Unicode.GetPreamble()); 
      StringWriter sw = new StringWriter(); 
      sw.WriteLine("\"FullName\",\"Position\",\"BranchOffice\",\"PrivateEmail\""); 
      foreach (var line in db.Persons) 
      { 
       sw.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", 
              line.FullName, 
              line.Position, 
              line.BranchOffice, 
              line.PrivateEmail); 
      } 
      Response.Write(sw.ToString()); 
      Response.End(); 
     } 

私はApiControllerでそれを使用したいのですが、ApiControllerでメンバーはありませんレスポンスどのように交換することができますか? HttpResponseMessageがありますが、同じことをすることはできません。
ありがとうございました!

答えて

1

次のコードは同等である必要があります。

var sw = new StringWriter(); 
sw.WriteLine("\"FullName\",\"Position\",\"BranchOffice\",\"PrivateEmail\""); 
foreach (var line in db.Persons) 
{ 
    sw.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", 
     line.FullName, 
     line.Position, 
     line.BranchOffice, 
     line.PrivateEmail); 
} 

return new HttpResponseMessage 
{ 
    Content = new StringContent(sw.ToString(), Encoding.Unicode) 
    { 
     Headers = 
     { 
      ContentType = new MediaTypeHeaderValue("text/csv"), 
      ContentDisposition = new ContentDispositionHeaderValue("attachment") 
      { 
       FileName = "Exported_Contacts.csv" 
      } 
     } 
    }, 
    StatusCode = HttpStatusCode.OK 
}; 
+0

どうもありがとう!それは実際に動作します! – Bodryi

関連する問題