c# - 在代码的其他部分使用变量的值 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"));
}
解决方案
查看IOption<T>
模式
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-5.0
- 创建一个包含您的 Path 属性的类
- 呼入
Configure<YourClass>(Configuration.GetSection("YourSection");
_ConfigureServices
- 注入
IOptions<YourClass>
你的控制器
如果您不想将该部分添加到配置文件中,它还支持类中的默认值,您可以根据配置设置覆盖这些默认值。
推荐阅读
- laravel - Laravel - Unknown column 'subscription_date' in 'group statement'
- java - 在哪里可以找到用于外来字符电子邮件验证的 Java 正则表达式 (RFC 6530)?
- javascript - React 创建一个二维码组件 将其转换为 base64 图像
- google-apps-script - 尝试保存到数组时导致此“无法设置属性”错误的原因是什么?
- javascript - 如何在 Phaser 3 中将数据从一个场景传递到另一个场景?
- c++11 - Qt:QObject::connect:没有这样的插槽
- powershell - 等待其他会话中的多个同时执行的 powershell 命令完成,然后再运行下一个命令
- web-scraping - 如何修复 yaml 文件中的“在此上下文中不允许映射值”错误?
- php - 测试父方法时存根子方法失败
- excel - 对数据进行排序后,我可以在 Excel 中将多行合并为一行吗?