[英]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
Configure<YourClass>(Configuration.GetSection("YourSection");
在ConfigureServices
IOptions<YourClass>
如果您不想将该部分添加到配置文件中,它还支持类中的默认值,您可以根据配置设置覆盖这些默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.