簡體   English   中英

在 ASP.NET CORE 代碼的其他部分使用變量的值

[英]Using the value of a variable in other parts of the code ASP.NET CORE

我正在制作一個 API,它有一個帶有ContentPath變量的Video實體。

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

查看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>

如果您不想將該部分添加到配置文件中,它還支持類中的默認值,您可以根據配置設置覆蓋這些默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM