c# - 是否可以访问 C# REST API 控制器中的非静态对象?
问题描述
是否可以访问 C# REST API 控制器中的非静态对象?
对于描述:
我想为一个项目编写一个 REST-API。数据来自数据库。但我不想每次触发请求时都询问数据库。所以我有一个与数据库对话并缓冲结果的对象“gen”。
我直接从一开始就创建了对象,它使自己保持活力并刷新了他的内部数据。
但是如何将对象提供给 REST-Controller (ValuesController) ?
我不想每次有人想要新数据时都创建对象。
示例代码:
namespace GenAPI
{
public class Program
{
public static void Main(string[] args)
{
GenAPI gen = new GenAPI(); // gen.table is the object of intrest
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
var wh = WebHost.CreateDefaultBuilder(args);
wh.UseUrls("http://*:4999");
wh.UseSetting("windowsAuthentication", "false");
wh.UseSetting("anonymousAuthentication", "true");
var iwh = wh.UseStartup<Startup>().Build();
return iwh;
}
}
public class Startup
{
public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseMvc();
}
}
}
namespace GenAPI.Controllers
{
[Route("")]
public class ValuesController : Controller
{
//[HttpGet]
//public IEnumerable<string> Get()
//{
// return new string[] { "value1", "value2" };
//}
[HttpGet("{url}")]
public IEnumerable<string> Get(string url)
{
List<string> result = new List<string>();
//foreach (var r in gen.table.Rows) // <-- Here I want do get the data
// result.Add(r[0]);
return result;
}
[HttpPost]
public void Post([FromBody]string value)
{
}
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
解决方案
我们有相同的要求,我们所做的是创建一个具有静态属性的 Global 类,该属性是缓存的数据:
public class Global
{
private static CacheObject _cache;
public static CacheObject cacheObject
{
get
{
if(_cache == null)
{
InitializeCacheObject();
}
return _cache;
}
set
{
_cache=Value;
}
}
public void InitializeCacheObject()
{
//get your data from db
CacheObject = db.getData();
}
}
在您的控制器中,您可以这样做:
var model = Global.CacheObject.Rows.ToList();
推荐阅读
- python - 错误:尝试发送电子邮件时,视图未返回 HttpResponse
- javascript - 是的验证:根据另一个字段值有条件地验证一个字段
- python - 如何将 Stringvar 转换为日期
- javascript - 有没有办法使用节点将较小的 PDF 文件插入到较大的 PDF 页面中?
- javascript - 将旋转元素的中心移动到光标
- javascript - useState 向对象添加属性只剩下最后一个属性
- gradle - 错误:尝试在 jitpack 上构建我的 gradle 项目时未找到构建工件
- java - 有什么方法可以根据我们的输入链接到该网站?
- laravel - 创建用户时,给role_id分配UUID
- bash - Docker 文件没有 /bin/bash 目录