安全文件下载

时间:2017-12-14 06:25:30

标签: file-upload asp.net-core-webapi aspnetboilerplate

我正在尝试使用.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图层中执行此操作

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

@tiennguyen回答是正确的。

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

 [AbpMvcAuthorize]
 [Route("api/[controller]/[action]")]
 public class  DownloadController : ProjectControllerBase
 {          
    public FileResult DownloadYourFile()
    {
            ....       
    }    
 }

答案 2 :(得分:0)

要从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);
}