Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File upload 安全文件下载_File Upload_Asp.net Core Webapi_Aspnetboilerplate - Fatal编程技术网

File upload 安全文件下载

File upload 安全文件下载,file-upload,asp.net-core-webapi,aspnetboilerplate,File Upload,Asp.net Core Webapi,Aspnetboilerplate,我正在尝试使用.net核心web api和angular 2.0在aspnetboilerplate模板中开发一个安全的文件下载 我在Web.host中尝试了这个,但它没有被当作API处理 public class DownloadController : ProjectControllerBase { private IHostingEnvironment _env; public FileResult DownloadYourFile()

我正在尝试使用.net核心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 layer中执行此操作要在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


获取更多细节

@tiennguyen的答案是正确的

Swagger不显示非常规的方法名称。因此,您必须写入[Route]属性。大摇大摆地被列入名单并不重要。你可以采取行动

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

要从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"
    });
});
在创建方法时获取服务中所需的文件

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
    };
}
添加从服务返回文件的方法

private string GetMimeType(string fileName)
{
    var provider = new FileExtensionContentTypeProvider();
    string contentType;
    if (!provider.TryGetContentType(fileName, out contentType))
    {
        contentType = "application/octet-stream";
    }
    return contentType;
} 
[SwaggerResponse(200, typeof(FileContentResult))]
[ProducesResponseType(typeof(FileContentResult), 200)]
public FileContentResult DownloadDocument(string fileName)
{
    // Call the method in Step 3
    return this._service.GetFile(fileName);
}

你所说的
不被视为API
是什么意思?@aaron它没有大摇大摆地显示出来。我如何在web.application中编写它?如果它以招摇过市的方式出现,任何想法都足够了吗?在应用层这样做既不琐碎,也不推荐,而且这样做并没有实际的好处。@aaron不,它不会出现在APIs中。这个问题解决了吗?