首页 > 解决方案 > 在代码的其他部分使用变量的值 ASP.NET CORE

问题描述

我正在制作一个 API,它的Video实体有一个ContentPath变量。

    public class Video
    {
        public string ContentPath { get; set; }
    }

这个变量是一个通过 POST/PUT 请求插入的字符串,理想情况下它应该是我要下载的某个文件的路径。

例如:{ "ContentPath":"Files/Image.png" }

我的问题是:如何ContentPath在解决方案的其他部分使用变量的值?更具体地说,我需要替换"Files/Image.png"以下代码块中的字符串。

控制器:

    [Route("api/servers/{serverId}/videos")]
    [ApiController]
    public class VideosController : ControllerBase
    {
        private readonly string filePath;
        public VideosController(string filePath)
        {
            this.filePath = filePath;
        }

        [HttpGet("{id}/binary")]
        public FileContentResult GetBinary()
        {
            // I need to replace the string "Files/Image.png" here for the ContentPath variable.
            return File(System.IO.File.ReadAllBytes(filePath), "application/octet-stream", "Files/Image.png");
        }
    }

启动.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<ServerContext>(opt => opt.UseInMemoryDatabase("Server"));
            services.AddDbContext<VideoContext>(opt => opt.UseInMemoryDatabase("Video"));
            // I need to replace the string "Files/Image.png" here for the ContentPath variable.
            services.AddSingleton(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Files/Image.png"));
        }

标签: c#asp.net-web-api

解决方案


查看IOption<T>模式

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-5.0

  1. 创建一个包含您的 Path 属性的类
  2. 呼入Configure<YourClass>(Configuration.GetSection("YourSection");_ConfigureServices
  3. 注入IOptions<YourClass>你的控制器

如果您不想将该部分添加到配置文件中,它还支持类中的默认值,您可以根据配置设置覆盖这些默认值。


推荐阅读