ASP.NET核心SignalR存取权限枢纽方法在任何地方

问题描述 投票:1回答:1

如果已经在这个问题上花费很多时间,我发现了很多不同的策略,但他们没有为我工作。 (此代码只是一个概念验证ofcourse)。

我一直在使用Asp.net 2.1核心下列设置(.Net的Framwork 4.7.2):

我已经由具有发送号码的方法的signalr毂:

using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;


namespace TestRandomNumberSignalR
{
    public class TestHub : Hub
    {
        public async Task SendRandomNumber(int number)
        {
            await Clients.All.SendAsync("ReceiveRandomBumber", number);
        }
    }
}

我还做了一个类更新一个随机数,每3秒,增加一条,作为一个单身:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TestRandomNumberSignalR
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new UpdateRandomNumber());
            services.AddSignalR();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
            app.UseSignalR(routes =>
            {
                routes.MapHub<TestHub>("/testHub");
            });
        }
    }
}

这里是随机数类:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace TestRandomNumberSignalR
{
    public class UpdateRandomNumber
    {
        private bool _continue = true;

        public UpdateRandomNumber()
        {
            var task = new Task(() => RandomNumberLoop(),
                                TaskCreationOptions.LongRunning);
            task.Start();
        }

        private void RandomNumberLoop()
        {
            Random r = new Random();

            while (_continue)
            {
                Thread.Sleep(3000);
                int number = r.Next(0, 100);
                Console.WriteLine("The random number is now " + number);

                // Send new random number to connected subscribers here
                // Something like TestHub.SendRandomNumber(number);

            }
        }

        public void Stop()
        {
            _continue = false;
        }
    }
}

现在,从这个类(正如我在评论中写道)我想给使用SignalR新的随机数。只有如何让枢纽背景在那里?

此外,我希望能够到控制器内访问类的stop()方法,我怎么可以访问?

我现在这是一个好讨论的话题,但我仍然不能在任何地方找到一个可行的解决方案。希望您能够帮助我。

编辑

问题1

而随机循环已开始(与许多感谢rasharasha),还存在一些问题依然存在。我现在无法注射合适的UpdateRandomNumber到控制器。可以说,我希望能够停止循环调用UpdateRandomNumber.Stop()方法,我怎么能注入UpdateRandomNumber单到控制器。我试图创建一个界面:

public interface IUpdateRandomNumber
{
    void Stop();
}

更改RandomNumber方法来实现这一点:

public class UpdateRandomNumber : IUpdateRandomNumber
{
    private bool _continue = true;

    private IHubContext<TestHub> testHub;

    public UpdateRandomNumber(IHubContext<TestHub> testHub)        
    {
        this.testHub = testHub;

        var task = new Task(() => RandomNumberLoop(),
                            TaskCreationOptions.LongRunning);
        task.Start();
    }

    private void RandomNumberLoop()
    {
        Random r = new Random();

        while (_continue)
        {

            Thread.Sleep(3000);
            int number = r.Next(0, 100);
            Console.WriteLine("The random number is now " + number);

            // Send new random number to connected subscribers here
            // Something like TestHub.SendRandomNumber(number);

        }
    }

    public void Stop()
    {
        _continue = false;
    }
}

并改变addsingleton方法,因此将使用的接口:

        services.AddSingleton<IUpdateRandomNumber>(provider =>
        {
            var hubContext = provider.GetService<IHubContext<TestHub>>();
            var updateRandomNumber = new UpdateRandomNumber(hubContext);
            return updateRandomNumber;
        });

我现在可以用一种方法来阻止randomnumber循环创建一个控制器:

[Route("api/[controller]")]
[ApiController]
public class RandomController : ControllerBase
{
    private readonly IUpdateRandomNumber _updateRandomNumber;

    public RandomController(IUpdateRandomNumber updateRandomNumber)
    {
        _updateRandomNumber = updateRandomNumber;
    }

    // POST api/random
    [HttpPost]
    public void Post()
    {
        _updateRandomNumber.Stop();
    }

然而,这种实现将阻止循环重新开始。那么,如何从控制器访问随机数单?

问题2

从我UpdateRandomNumber类我现在就可以拨打:

testHub.Clients.All.SendAsync("ReceiveRandomBumber", number);

但是为什么我在做我的testhub的方法:

    public async Task SendRandomNumber(int number)
    {
        await Clients.All.SendAsync("ReceiveRandomBumber", number);
    }

这将是更方便地创建轮毂的方法和他们直接调用它们。可以这样做?

c# asp.net-core dependency-injection asp.net-core-signalr
1个回答
4
投票

您可以注入到TestHub使用构造器注入控制器。自从与已登记注册的DI容器。

public class UpdateRandomNumber
{
    private bool _continue = true;
    private IHubContext<TestHub> testHub;
    private Task randomNumberTask;
    public UpdateRandomNumber(IHubContext<TestHub> testHub)
    {
        this.testHub=testHub;
        randomNumberTask = new Task(() => RandomNumberLoop(),
            TaskCreationOptions.LongRunning);
        randomNumberTask.Start();
    }
    private async void RandomNumberLoop()
    {
        Random r = new Random();

        while (_continue)
        {
            Thread.Sleep(3000);
            int number = r.Next(0, 100);
            Console.WriteLine("The random number is now " + number);

            // Send new random number to connected subscribers here
             await testHub.Clients.All.SendAsync($"ReceiveRandomNumber", number);

        }
    }

    public void Stop()
    {
        _continue = false;
    }
}
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        services.AddSignalR();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddSingleton(provider =>
        {
            var hubContext = provider.GetService<IHubContext<TestHub>>();
            var updateRandomNumber = new UpdateRandomNumber(hubContext);
            return updateRandomNumber;
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var updateRandonNumber = app.ApplicationServices.GetService<UpdateRandomNumber>();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();
        app.UseSignalR(routes =>
        {
            routes.MapHub<TestHub>("/testHub");
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.