【发布时间】: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