如何从appsettings读取值.并将其与实体框架返回的值混合



早上好,我有一个项目在Asp.net Core 5有一个核心项目与实体。我的问题是,我需要知道如何将News类的属性与托管在另一个ASP中的值混合。Net Core API项目。也就是说,当从Entity返回值时,您必须能够混合应用设置的值。Json +图像字段

即,在GetNoticiacastList()方法中,我需要FullPath属性与appsettings的值和image属性的值混合使用。生成

的URL我appsettings.json

"AppSettings": {
"virtualpath": "//google.com/photos/"

},

我的类:

public class Noticia
{
public int  id{ get; set; }
public string Titulo { get; set; }
public string Imagen { get; set; }
public string FullPath { get; set; }
}
我NoticiaRepository

:

public async Task<IEnumerable<Noticia>> GetNoticiacastList()
{
var listadoNoticia = await _context.Noticia.ToListAsync();
return listadoNoticia ;
}

将配置映射到类是一个好主意。

StorageOption.cs(创建此文件)

public class StorageOption
{
public string VirtualPath { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<StorageOption>(Configuration.GetSection("AppSettings"));
....
}

NoticiaRepository.cs

public class NoticiaRepository : INoticiaRepository
{
private readonly AppDbContext _context;
private readonly StorageOption _storageOption;
...
public NoticiaRepository(AppDbContext context, IOptions<StorageOption> storageOption)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
_storageOption = storageOption?.Value ?? throw new ArgumentNullException(nameof(storageOption));
}
...
public async Task<IEnumerable<Noticia>> GetNoticiacastList()
{
var listadoNoticia = await _context.Noticia.ToListAsync();
return listadoNoticia.Select(item => { item.FullPath = $"{_storageOption.VirtualPath}{item.Imagen}"; return item; });
}
...
}

最新更新