首先,我对我的英语水平感到非常抱歉。
我目前正在通过 dotnet core 3.1 blazor 开发一个 Web 项目。
如下面的源代码所示,我使用 IJSRuntime 调用需要很长时间的 Javascript 函数。
[Inject]
IJSRuntime JSRuntime { get; set; }
private async Task BtnDisplay()
await JSRuntime.InvokeVoidAsync("RefreshWebJS", Data);
}
Run Code Online (Sandbox Code Playgroud)
Javascript 函数需要很长时间,因此我添加了下面的源代码来添加微调器。
private async Task BtnDisplay()
{
showLoadingImg = true; // add
await JSRuntime.InvokeVoidAsync("RefreshWebJS", Data);
showLoadingImg = false;
}
Run Code Online (Sandbox Code Playgroud)
Spinner 在 razor 页面上定义如下:
@if (showLoadingImg == true)
{
<div style="position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; text-align: center;">
<img src="/images/LoadingImg.gif" style="position: absolute; top: 50%; left: 50%;" />
</div> …Run Code Online (Sandbox Code Playgroud) blazor asp.net-core-signalr asp.net-core-3.1 blazor-jsinterop
因此,我遵循了一些教程,一旦您设置了集线器,常见的主题之一C#就是调用与此类似的服务:
private hubConnection: signalR.HubConnection = new signalR.HubConnectionBuilder()
.withUrl(`${environment.hub}contacts`)
.build();
constructor(private http: HttpClient) {
}
public startConnection = () =>
this.hubConnection
.start()
.then(() => console.log('Hub Connection started'))
.catch(err => console.log('Error while starting connection: ' + err))
public addTransferContactDataListener = () =>
this.hubConnection.on('transfercontactdata', (data) => {
this.contacts = data.result // where the magic happens on the push
console.log(data, 'Hub data transfer occuring');
});
Run Code Online (Sandbox Code Playgroud)
我担心的是,如果你尝试private hubConnection: signalR.HubConnection在构造函数中注入它,它就会崩溃。即使您设置了连接生成器。这很重要,因为如果我想要四页或更多页全部内容怎么办subscribe?
我一直在做的是在 中设置服务,然后调用和 then 的app.component.ts方法。但这似乎是错误的。我试图将其注入到模块中,但它一直失败,说它没有或有其他东西。虽然它是可注入的,但您仍然必须调用它,并且构造函数有时在我的实践中似乎被忽略。startConnectionaddTransferContactDataListenerprovider
有没有人深入研究过在注入时调用并设置它并重用它? …
我正在开发一个简单的 .NET 6 应用程序,以在我们的前端应用程序中启用数据更新通知。我之前在 .NET 5 中构建过类似的东西,但我遇到了一个让我困惑的 DI 问题。在 5 中,自动映射的所有集线器都有一个 IHubContext,该 IHubContext 也在容器中为它们设置。到了 6 后,情况似乎不再如此。
System.InvalidOperationException:尝试激活“SignalRNotifications.Controllers.NotificationController”时无法解析类型“Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]”的服务。
6 中新的非启动 DI 对我来说看起来很奇怪,但我只是没有看到任何可用的内容说明如何修复它。关于如何将 IHubContext 注入我的控制器有什么建议吗?
谢谢!
更新:这是一些相关代码:
using Microsoft.AspNetCore.Builder;
using SignalRNotifications.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSignalR().AddAzureSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/NotificationHub");
});
app.Run();
Run Code Online (Sandbox Code Playgroud)
依赖注入是在控制器中以最可预测的方式完成的:
using Microsoft.AspNetCore.Builder;
using SignalRNotifications.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddSignalR().AddAzureSignalR();
var app …Run Code Online (Sandbox Code Playgroud) dependency-injection asp.net-core asp.net-core-signalr .net-6.0
我在OpenIddict的ASP.NET Core 2.0应用程序中使用JWT身份验证.
我在SignalR握手后跟踪这个线程和调用AuthorizeWithJWT方法的想法.但是现在,我不知道我应该在AuthorizeWithJWT方法中设置什么,所以我可以使用它[Authorize(Roles="Admin")].
我试着设置上下文用户,但它只是readonly:
public class BaseHub : Hub
{
public async Task AuthorizeWithJWT(string AccessToken)
{
//get user claims from AccesToken
this.Context.User = user; //error User is read only
}
}
Run Code Online (Sandbox Code Playgroud)
并使用authorize属性:
public class VarDesignImportHub : BaseHub
{
[Authorize(Roles = "Admin")]
public async Task Import(string ConnectionString)
{
}
}
Run Code Online (Sandbox Code Playgroud) 当我调用 Hub 方法时,我得到帧响应:
{"invocationId":"1","type":3,"error":"更新条目时出错。有关详细信息,请参阅内部异常。"}
如何在不手动调试和使用 step over 的情况下获得详细的错误报告(发生错误的行和文件)并检查代码引发异常的位置。
在网上我发现了很多代码在哪里EnableDetailedErrors使用
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
Run Code Online (Sandbox Code Playgroud)
但是选项(至少在 1.0.0-alpha2-final 版本中)没有属性集线器。
尝试按照以下链接中的建议将JWT令牌传递到我的 SignalR 集线器,但到目前为止它不起作用。具体参见 David Fowler 在 2017 年 7 月 22 日的建议。https://github.com/aspnet/SignalR/issues/130
我的前端是React这样,我只是将令牌添加到查询字符串中,如下所示,其中_token有我的JWT令牌值:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/myhub?AUTHORIZATION=" + _token)
.configureLogging(signalR.LogLevel.Information)
.build();
Run Code Online (Sandbox Code Playgroud)
在ConfigureServices()my的方法中Startup.cs,我对Jwt令牌进行了以下配置:
services.AddAuthentication(options => {
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions => {
jwtOptions.Authority = $"https://login.microsoftonline.com/tfp/{Configuration["AzureAdB2C:Tenant"]}/{Configuration["AzureAdB2C:Policy"]}/v2.0/";
jwtOptions.Audience = Configuration["AzureAdB2C:ClientId"];
jwtOptions.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
if(context.HttpContext.WebSockets.IsWebSocketRequest)
context.Token = context.Request.Query["AUTHORIZATION"];
return Task.CompletedTask;
}
};
});
Run Code Online (Sandbox Code Playgroud)
这就是我的Hub样子:
[Authorize]
public class …Run Code Online (Sandbox Code Playgroud) 用户在浏览器中提交表单后,我需要从服务器向客户端发送即时消息。
我按照Microsoft的步骤在此处建立了signalR连接,创建了Hub类,signalr.js等。
问题是我只能向所有客户端调用一条消息,但是我需要向发起请求的特定调用者调用该消息(否则每个人都会收到该消息)。
这是我在HomeController.cs中的POST操作:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Submit(string signalRconnectionId, Dictionary<string, string> inputs)
{
//Invoke signal to all clients sending a message to initSignal WORKS FINE
await _signalHubContext.Clients.All.SendAsync("initSignal", "This is a message from the server!");
//Invoke signal to specified client where signalRConnectionId = connection.id DOES NOT WORK
await _signalHubContext.Clients.Client(signalRconnectionId).SendAsync("initSignal", "This is a message from server to this client: " + signalRconnectionId);
return RedirectToAction("Success", inputs);
}
Run Code Online (Sandbox Code Playgroud)
我的客户javascript文件:
//Create connection and start it
const connection = new signalR.HubConnectionBuilder()
.withUrl("/signalHub") …Run Code Online (Sandbox Code Playgroud) 我正在尝试从 (ASP.NET Core) MVC 控制器调用信号集线器类中的方法,但我无法在网上找到演示如何操作的示例。
注意:有很多示例在 .Net 框架中使用旧版本的信号器,但我看不到任何示例都显示了如何在 .Net Core 中执行此操作。
我需要将 MVC 操作结果中的 id 直接传递到我的集线器,而不是将 id 传递到页面,然后必须将客户端连接返回到集线器。
public class ChatHub : Hub
{
public async Task DoSomething(int id)
{
//// Something in here.
}
}
public class HomeController : Controller
{
private readonly IHubContext<ChatHub> _hubContext;
public HomeController(IHubContext<ChatHub> hubContext)
{
_hubContext = hubContext;
}
public async Task<ActionResult> Index(int id)
{
//// Call the DoSomething method from here, passing the id across.
await _hubContext.Clients.All.SendAsync("AddToGroup", groupId);
}
}
Run Code Online (Sandbox Code Playgroud)
请问有没有办法做到这一点?(或者我是否以错误的方式看待这个问题,是否有更好的方法来实现相同的结果?)
更新:如果我将 Id …
c# signalr signalr-hub asp.net-core-mvc asp.net-core-signalr
我正在尝试将请求从服务器发送到客户端(.Net),该客户端在文化特定环境中运行,这会影响特殊时区的日期。
我从服务器发送未指定类型的日期,以避免在客户端检索时对其进行转换。基本上我只是在服务器端像这样转换它:
DateTime dateToSend = DateTime.SpecifyKind(serverSideDate, DateTimeKind.Unspecified);
Run Code Online (Sandbox Code Playgroud)
问题是,当客户端使用JsonProtocol时,日期没有被转换并且得到正确处理,而对于MessagePackProtocol,客户端和服务器端的相同代码的工作方式完全不同 - 它将日期转换为客户端上的文化特定时区。 。
如何防止这种转换,而不需要一些黑客解决方案,例如将日期作为字符串传递。
更新:
正如 Shaun 所建议的,我已经以这种方式在客户端和服务器端配置了 MessagePack,但不幸的是它仍然无法正常工作:
.AddMessagePackProtocol(options =>
options.FormatterResolvers = new List<MessagePack.IFormatterResolver>()
{
StandardResolver.Instance,
NativeDateTimeResolver.Instance
})
Run Code Online (Sandbox Code Playgroud) msgpack signalr signalr.client asp.net-core asp.net-core-signalr
signalr ×6
asp.net-core ×3
c# ×3
signalr-hub ×2
.net-6.0 ×1
angular ×1
asp.net-mvc ×1
blazor ×1
msgpack ×1
openiddict ×1