安全文件下载

问题描述 投票:0回答:3

我正在尝试使用.net core web api和angular 2.0在aspnetboilerplate模板中开发安全的文件下载

我在Web.host上试过这个,但它没有被视为API

public class DownloadController : ProjectControllerBase
    {
        private IHostingEnvironment _env;
        public FileResult DownloadYourFile()
        {
            try
            {
                long uid = (AbpSession.UserId == null) ? 0 : Convert.ToInt64(AbpSession.UserId);
                var net = new System.Net.WebClient();
                string path = Path.Combine(_env.WebRootPath, "downloads/xyz.doc");                                     
                var data = net.DownloadData(path);
                var content = new System.IO.MemoryStream(data);
                var contentType = "APPLICATION/octet-stream";
                var fileName = "xyz.doc";
                return File(content, contentType, fileName);
            }
            catch (Exception e)
            {
                throw new UserFriendlyException("Error", "Error downloading file. Please try again.", e);
            }            
        }

    }

我怎么能在Web.Application层中做到这一点

file-upload asp.net-core-webapi aspnetboilerplate
3个回答
1
投票

要从Nuget安装的软件包

1. Microsoft.AspNetCore.StaticFiles // To Get MimeType
2. NSwag.Annotations // Map API Return Type to NSwag Generate Method Return Type

然后在Startup.cs中的ConfigureServices方法中,

services.AddSwaggerGen(options =>
{
    // Swagger Configurations
    options.MapType<FileContentResult>(() => new Schema
    {
        Type = "file"
    });
});

添加一个方法来获取服务中文件的MimeType

private string GetMimeType(string fileName)
{
    var provider = new FileExtensionContentTypeProvider();
    string contentType;
    if (!provider.TryGetContentType(fileName, out contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;
} 

在服务中获取所需文件以创建方法

public FileContentResult GetFile(string filename)
{
   // _environment is instance of IHostingEnvironment
    var filepath = Path.Combine($"{this._environment.WebRootPath}\\PATH-TO-FILE\\{filename}");

    // Get the MimeType of file
    var mimeType = this.GetMimeType(filename);
    byte[] fileBytes;
    if (File.Exists(filepath))
    {
        fileBytes = File.ReadAllBytes(filepath); 
    } 
    else
    {
        throw new Exception("File Not Found");
    }

    return new FileContentResult(fileBytes, mimeType)
    {
        FileDownloadName = filename
    };
}

添加一个从服务返回文件的方法

[SwaggerResponse(200, typeof(FileContentResult))]
[ProducesResponseType(typeof(FileContentResult), 200)]
public FileContentResult DownloadDocument(string fileName)
{
    // Call the method in Step 3
    return this._service.GetFile(fileName);
}

0
投票

要在Swagger中显示新方法,您可以这样做:

[Route("api/[controller]/[action]")] //Should add route config for your controller
public class TestController : AbpCoreControllerBase
{
    [HttpGet] //Should add HttpMethod to your method
    public string TestMethod()
    {
       return "Hello world";
    }
}

为了确保文件下载,我认为你可以做到:

  • 将AbpAuthorize属性添加到您的控制器/方法
  • 如果需要手动检查权限,请注入PermissionChecker

获取更多细节here


0
投票

@tiennguyen答案是正确的。

Swagger没有显示非传统的方法名称。所以你必须写[Route]属性。在Swagger上市并不是一件轻而易举的事。你可以调用这个动作。

 [AbpMvcAuthorize]
 [Route("api/[controller]/[action]")]
 public class  DownloadController : ProjectControllerBase
 {          
    public FileResult DownloadYourFile()
    {
            ....       
    }    
 }
© www.soinside.com 2019 - 2024. All rights reserved.