【问题标题】:Using the value of a variable in other parts of the code ASP.NET CORE在代码的其他部分使用变量的值 ASP.NET CORE
【发布时间】:2021-12-09 09:15:18
【问题描述】:

我正在创建一个具有 Video 实体的 API,该实体具有 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");
        }
    }

Startup.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"));
        }

【问题讨论】:

  • 对于 startup.cs 代码,您可以在 appsettings.json 文件中定义值并从那里读取。对于 get 方法,您需要将变量作为参数传递给方法
  • 你不能把这个路径保存在数据库中吗?执行此操作的所有其他方式都会在应用程序重新启动时重置此值,或者不支持拥有多个实例。在 POST 调用中设置此值也会破坏 GetBinary() 调用的幂等性。有没有其他方法可以做到这一点?

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


【解决方案1】:

查看IOption&lt;T&gt; 模式

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

  1. 创建一个包含您的 Path 属性的类
  2. ConfigureServices 中致电Configure&lt;YourClass&gt;(Configuration.GetSection("YourSection");
  3. 在控制器中注入 IOptions&lt;YourClass&gt;

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

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多