asp.net 从Razor视图中获取绑定的URL

hi3rlvi2  于 2023-10-21  发布在  .NET
关注(0)|答案(2)|浏览(139)

我想从Razor Pages视图中显示我的Web服务器的绑定URL。我可以从Main中访问它们,如下所示:

var builder = WebApplication.CreateBuilder(args);
    //...
    var app = builder.Build();
    //...
    await app.StartAsync();
    //...
    // Debug here...

.通过在“在此添加断点并检查app.Urls(应用程序是Microsoft.AspNetCore.Builder.WebApplication),但我不能在DI配置期间添加此内容,因为它只在StartAsync之后填充。那么,我如何才能从该Web应用程序中运行的Razor Pages视图中访问这些信息呢?

ulmd4ohb

ulmd4ohb1#

创建一个自定义配置类来保存URL。

public class WebServerUrls
{
    public List<string> Urls { get; set; } = new List<string>();
}

Program.cs文件中,将此自定义配置类的注册添加为单例服务:

builder.Services.AddSingleton<WebServerUrls>();
// ...

var builder = WebApplication.CreateBuilder(args);
// ...

var app = builder.Build();
// ...

await app.StartAsync();
var webServerUrls = app.Services.GetRequiredService<WebServerUrls>();
webServerUrls.Urls.AddRange(app.Urls);

// ...

在Razor Pages视图中,使用@inject指令注入WebServerUrls类并访问绑定的URL:

@page
@model YourPageModel

@inject WebServerUrls WebServerUrls

<h1>Bound URLs</h1>

<ul>
    @foreach (var url in WebServerUrls.Urls)
    {
        <li>@url</li>
    }
</ul>
cwdobuhd

cwdobuhd2#

要在Razor Pages视图中显示Web服务器的绑定URL,请创建一个服务来存储和访问此信息,然后将该服务数据注入Razor视图。

  • 服务 *:
public class WebServerInfoService : IWebServerInfoService
{
    private readonly List<string> boundUrls = new List<string>();
    private readonly object lockObject = new object();

    public void AddBoundUrl(string url)
    {
        lock (lockObject)
        {
            boundUrls.Add(url);
        }
    }

    public List<string> GetBoundUrls()
    {
        lock (lockObject)
        {
            return boundUrls.ToList(); // Return a copy of the list to prevent modification by consumers
        }
    }
}
  • 主要内容:*
app.UseUrls(urls =>
    {
        foreach (var url in urls)
        {
            webServerInfoService.AddBoundUrl(url);
        }
    });
  • 剃刀视图:*
@inject IWebServerInfoService webServerInfoService

<!DOCTYPE html>
<html>
<head>
    <title>Bound URLs</title>
</head>
<body>
    <h1>Bound URLs</h1>
    <ul>
        @foreach (var url in webServerInfoService.GetBoundUrls())
        {
            <li>@url</li>
        }
    </ul>
</body>
</html>

相关问题