.NET Blazor Server部署IIS后返回空集合问题求助
问题:Blazor Server部署到IIS后无法获取显示器信息
我使用.NET Blazor Server实现数据绑定,目标是列出系统中所有可用显示器。从新项目开始简化实现,编写了以下代码:
模型类
using CommunityToolkit.Mvvm.ComponentModel; namespace BindingTest.Data; public class DisplayInfo : ObservableObject { private string deviceName = string.Empty; public string DeviceName { get { return deviceName; } set { deviceName = value; OnPropertyChanged(nameof(DeviceName)); } } private bool primary; public bool Primary { get { return primary; } set { primary = value; OnPropertyChanged(nameof(Primary)); } } }
服务类
using System.Collections.ObjectModel; using WindowsDisplayAPI; namespace BindingTest.Data; public class DisplayService { public ObservableCollection<DisplayInfo> ScreenCollection { get; set; } = new(); public DisplayService() { foreach (Display display in Display.GetDisplays()) { ScreenCollection.Add(new DisplayInfo { DeviceName = display.DisplayName, Primary = display.IsGDIPrimary, }); } } }
页面代码
@page "/displays" @using BindingTest.Data; @using System.Collections.ObjectModel; <PageTitle>Displays</PageTitle> @inject DisplayService display <h1>Display Service</h1> @if (display.ScreenCollection == null) { <p><em>Loading...</em></p> } else { <p>Total items in collection: @display.ScreenCollection.Count</p> <table class="table"> <thead> <tr> <th>Device Name</th> <th>Primary</th> </tr> </thead> <tbody> @foreach (var display in display.ScreenCollection) { <tr> <td>@display.DeviceName</td> <td>@display.Primary.ToString()</td> </tr> } </tbody> </table> }
Program.cs
using BindingTest.Data; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); builder.Services.AddSingleton<DisplayService>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); app.Run();
已启用WebSocket协议,项目已发布。以下两种场景运行正常:
- 在Visual Studio中使用IIS Express运行
- 直接运行发布文件夹中的.exe文件
但部署到IIS后,集合为空,无法获取显示器信息。请问是流程或代码存在问题,还是IIS的限制?同时希望能推荐相关教程。
内容的提问来源于stack exchange,提问作者Franck E
相关产品推荐
相关产品推荐

