[英]ASP.NET Core 6 MVC : how to access a variable's value that is defined in Program.cs from a controller?
I have created an ASP.NET Core 6 MVC application & I created a variable in my Program.cs
file and assigned it a random UUID value.我创建了一个 ASP.NET Core 6 MVC 应用程序,并在我的
Program.cs
文件中创建了一个变量并为其分配了一个随机 UUID 值。
I then use that variable as part of several endpoint routing patterns, also defined in my Program.cs
file.然后我将该变量用作多个端点路由模式的一部分,这些模式也在我的
Program.cs
文件中定义。
My question is, if I need to access that same variable and its UUID value from within my controller file, how do I go about doing that?我的问题是,如果我需要从我的 controller 文件中访问同一个变量及其 UUID 值,我该怎么做 go ?
I've tried researching how to create global variables & accessing them between .NET files - but none of those techniques seem to work for ASP.NET Core MVC application.我已经尝试研究如何创建全局变量并在 .NET 文件之间访问它们 - 但这些技术似乎都不适用于 ASP.NET Core MVC 应用程序。
Here is a code snippet from my Program.cs
file that shows the created variable ( uuid1
) and how it is used in some of the endpoints route patterns I would like to be able to access the variable uuid1
from within my HomeController
.这是我的
Program.cs
文件中的代码片段,它显示了创建的变量 ( uuid1
) 以及它如何在一些端点路由模式中使用我希望能够从我的HomeController
中访问变量uuid1
。 Thanks in advance.提前致谢。
app.UseEndpoints(endpoints =>
{
Guid uuidi = Guid.NewGuid();
string uuid1 = uuidi.ToString();
Console.WriteLine("UUID: " + uuid1);
endpoints.MapControllerRoute(name: "views",
pattern: uuid1,
defaults: new { controller = "Home", action = "Index" });
endpoints.MapControllerRoute(name: "views",
pattern: "/" + uuid1 + "/exit/",
defaults: new { controller = "Home", action = "Submitted" });
endpoints.MapGet("/uuid", async context =>
{
await context.Response.WriteAsync(uuid1);
});
According to your description, I suggest you could try to write a class which store the value and register it as Singleton service.根据您的描述,我建议您可以尝试编写一个 class 来存储该值并将其注册为 Singleton 服务。
Then you could use it inside the controller.然后你可以在 controller 中使用它。
More details, you could refer to below codes:更多详细信息,您可以参考以下代码:
Class: Class:
public class ChannelOptions
{
public string? ChannelId { get; set; }
}
Program.cs程序.cs
Guid uuidi = Guid.NewGuid();
string uuid1 = uuidi.ToString();
builder.Services.AddSingleton(new ChannelOptions { ChannelId = uuid1 });
Controller: Controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ChannelOptions options1;
public HomeController(ILogger<HomeController> logger, ChannelOptions options)
{
_logger = logger;
options1 = options;
}
public IActionResult Index()
{
var re = options1.ChannelId;
return View();
}
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.