Returning binary file from controller in ASP.NET Web API

后端 未结 8 772
离开以前
离开以前 2020-11-22 02:55

I\'m working on a web service using ASP.NET MVC\'s new WebAPI that will serve up binary files, mostly .cab and .exe files.

The following co

8条回答
  •  囚心锁ツ
    2020-11-22 03:46

    For Web API 2, you can implement IHttpActionResult. Here's mine:

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Http;
    
    class FileResult : IHttpActionResult
    {
        private readonly string _filePath;
        private readonly string _contentType;
    
        public FileResult(string filePath, string contentType = null)
        {
            if (filePath == null) throw new ArgumentNullException("filePath");
    
            _filePath = filePath;
            _contentType = contentType;
        }
    
        public Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(File.OpenRead(_filePath))
            };
    
            var contentType = _contentType ?? MimeMapping.GetMimeMapping(Path.GetExtension(_filePath));
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
    
            return Task.FromResult(response);
        }
    }
    

    Then something like this in your controller:

    [Route("Images/{*imagePath}")]
    public IHttpActionResult GetImage(string imagePath)
    {
        var serverPath = Path.Combine(_rootPath, imagePath);
        var fileInfo = new FileInfo(serverPath);
    
        return !fileInfo.Exists
            ? (IHttpActionResult) NotFound()
            : new FileResult(fileInfo.FullName);
    }
    

    And here's one way you can tell IIS to ignore requests with an extension so that the request will make it to the controller:

    
    
      
    

提交回复
热议问题