Как вернуть файл из веб-службы?

1

У меня есть стандартная служба WCF (.svc), которая обычно говорит JSON. Мне нужно создать метод для возврата PDF файла.

Я могу это сделать (теоретически, не пробовал)

public Byte[] GetDocument(string DocumentName)
{
  string strdocPath;
  strdocPath = "C:\\DocumentDirectory\\" + DocumentName;

  FileStream objfilestream = new FileStream(strdocPath,FileMode.Open,FileAccess.Read);
  int len = (int)objfilestream.Length;          
  Byte[] documentcontents  = new Byte[len];
  objfilestream.Read(documentcontents,0,len);
  objfilestream.Close();

  return documentcontents;  
} 

Но мне нужно указать имя файла, которое я не уверен, как это сделать в этом контексте.

В обычном asp.net mvc я бы сделал следующее:

Response.Clear();
Response.ClearHeaders();
Response.ContentType = file.ContentType;
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.FileName + "\"");
Response.AddHeader("Content-Length", file.FileSize.ToString());
Response.OutputStream.Write(file.Bytes, 0, file.Bytes.Length);
Response.Flush();
Response.End();

но объект Response, похоже, не существует в проекте WCF.

Я что-то пропустил?

  • 1
    Обратный Stream . Я думаю, вы можете использовать OperationContext или WebOperationContext, чтобы установить заголовки.
Теги:
pdf
wcf

1 ответ

2

Я использую его следующим образом:

string agent = WebOperationContext.Current.IncomingRequest.Headers["User-Agent"];

if (agent.Contains("MSIE") == false)
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "inline; filename=\"{0}\"".Fill(attachment.Filename));
}
else
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=\"{0}\"".Fill(attachment.Filename));
    WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Download-Options", "noopen");
    WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Content-Type-Options", "nosniff");
}

return new MemoryStream(attachment.Data);

Ещё вопросы

Сообщество Overcoder
Наверх
Меню