C# Код веб-API читает файл и открывает файл при возврате - PullRequest
0 голосов
/ 08 апреля 2020

Я смог использовать следующий код C# Web Api 2 для извлечения файла из пути и загрузки файла. Пользователь может загрузить файл ab c .pdf, используя этот URL http://localhost: 60756 / api / TipSheets / GetTipSheet? FileName = ab c .pdf . Я хотел бы изменить код, чтобы открыть файл, а не загружать его. Как я могу это сделать ?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using HttpGetAttribute = System.Web.Http.HttpGetAttribute;

namespace TestWebApi.Controllers
{
public class TipSheetsController : ApiController
{
    string tipSheetPath = @"C:\pdf\";
    string videoPath    = @"C:\video\";
    string clientIp;
    string clientIpSrc;

    public IHttpActionResult GetTipSheet(string fileName)
    {


        string ext = Path.GetExtension(fileName).ToLowerInvariant();
        string reqBook = (ext.Equals(".pdf")) ? tipSheetPath + fileName : videoPath + 
                          fileName;
        //string bookName = fileName;


        //converting Pdf file into bytes array
        try
        {
            var dataBytes = File.ReadAllBytes(reqBook);
            //adding bytes to memory stream 
            var dataStream = new MemoryStream(dataBytes);
            return new tipSheetResult(dataStream, Request, fileName);
        }
        catch (Exception)
        {

            throw;
        }
    }

}

public class tipSheetResult : IHttpActionResult
{
    MemoryStream bookStuff;
    string PdfFileName;
    HttpRequestMessage httpRequestMessage;
    HttpResponseMessage httpResponseMessage;
    public tipSheetResult(MemoryStream data, HttpRequestMessage request, string filename)
    {
        bookStuff = data;
        httpRequestMessage = request;
        PdfFileName = filename;
    }
    public System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)
    {
        httpResponseMessage = httpRequestMessage.CreateResponse(HttpStatusCode.OK);
        httpResponseMessage.Content = new StreamContent(bookStuff);            
        httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = PdfFileName;                        
        httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        return System.Threading.Tasks.Task.FromResult(httpResponseMessage);
    }

   }
}
...