是否可以在信号器中心内使用 IAsyncActionFilter?
Is it possible to to use an IAsyncActionFilter within a signalr hub?
使用 MVC aspnetcore 应用程序,我可以创建一个 IAsyncActionFilter 来测量执行时间(作为属性实现)。我想对 Signalr 集线器控制器执行相同的操作,但似乎不起作用。
public class TimeFilter : Attribute, IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
Stopwatch sw = new Stopwatch();
sw.Start();
await next();
sw.Stop();
string logStr = ($"##### {context.ActionDescriptor.DisplayName} - EXC: {sw.ElapsedMilliseconds}ms");
System.Diagnostics.Debug.WriteLine(logStr);
}
}
这有效(通过 MVC):
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[TimeFilter]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
失败(通过 Signalr,从未调用 TimeFilter):
public class SRHub : Hub
{
[TimeFilter]
public async Task Calc(int x, int y)
{
await Clients.Client(Context.ConnectionId).SendAsync("CalcResp", x+y);
}
}
我猜 SignalR 没有使用与 MVC 相同的流水线,但我是否遗漏了什么,或者这是不可能的?
您猜对了,SignalR 不使用与 MVC 相同的流水线。可以进行快速测试。
app.UseSignalR(routes =>
{
routes.MapHub<ChartHub>("/chart");
});
并注释掉
//app.UseMvc();
您会发现 signalR 仍然有效。
中间件似乎也不适用于此。
使用 MVC aspnetcore 应用程序,我可以创建一个 IAsyncActionFilter 来测量执行时间(作为属性实现)。我想对 Signalr 集线器控制器执行相同的操作,但似乎不起作用。
public class TimeFilter : Attribute, IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
Stopwatch sw = new Stopwatch();
sw.Start();
await next();
sw.Stop();
string logStr = ($"##### {context.ActionDescriptor.DisplayName} - EXC: {sw.ElapsedMilliseconds}ms");
System.Diagnostics.Debug.WriteLine(logStr);
}
}
这有效(通过 MVC):
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[TimeFilter]
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
失败(通过 Signalr,从未调用 TimeFilter):
public class SRHub : Hub
{
[TimeFilter]
public async Task Calc(int x, int y)
{
await Clients.Client(Context.ConnectionId).SendAsync("CalcResp", x+y);
}
}
我猜 SignalR 没有使用与 MVC 相同的流水线,但我是否遗漏了什么,或者这是不可能的?
您猜对了,SignalR 不使用与 MVC 相同的流水线。可以进行快速测试。
app.UseSignalR(routes =>
{
routes.MapHub<ChartHub>("/chart");
});
并注释掉
//app.UseMvc();
您会发现 signalR 仍然有效。 中间件似乎也不适用于此。