0
public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        this.Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    /// <summary>
    /// Используется для доступа к контексту SignalR хаба из любого класса
    /// IHubContext context = Startup.ConnectionManager.GetHubContext<CallQueueHub>();
    /// context.Clients.All.someMethod();
    /// </summary>
    //public static IConnectionManager ConnectionManager;

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        // Add framework services.
        services.AddMvc();
        services.AddAuthorization(options =>
        {   // доступ открыт только внутренним пользователям - специалистам.
            // https://docs.asp.net/en/latest/security/authorization/policies.html
            options.AddPolicy("OnlyEmployee", policy =>
            {
                policy.RequireAuthenticatedUser();
                policy.Requirements.Add(new OnlyEmployeeRequirement());
            });
        });

        services.AddSignalR(options =>
        {
            options.Hubs.EnableDetailedErrors = true;
        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton<IUserIdentityAccessor, UserIdentityAccessor>();
        services.AddSingleton<IAuthorizationHandler, OnlyEmployeeRequirementHandler>();
        services.AddSingleton<HttpClientProvider>();
        //services.AddSingleton<CallQueueHub>();

        services.AddOptions();  // https://docs.asp.net/en/latest/fundamentals/configuration.html
        services.Configure<AppSettings>(this.Configuration.GetSection("AppSettings"));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole(this.Configuration.GetSection("Logging")); // TODO: куда логи складываются? Создалось из шаблона. Надо исследовать.
        loggerFactory.AddDebug();
        //ConnectionManager = serviceProvider.GetService<IConnectionManager>();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseWebSockets();
        //app.UseSignalR<RawConnection>("/raw-connection");
        app.UseSignalR();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

Как подключить к ASP Core проекту SignalR?

15
  • Хотелось бы увидеть пример как подключить signalr и вызвать с серверного кода простой alert на клиенте
    – Alex
    29 апр 2017 в 18:42
  • Вам туториалов недостаточно? Реализовывайте сами, если возникнут проблемы или вопросы - добро пожаловать.
    – MihailPw
    29 апр 2017 в 18:59
  • Гуглил очень много, читал, изучал примерно неделю, но конкретной информации не нашёл
    – Alex
    29 апр 2017 в 19:01
  • нашёл как подключить Gray.Microsoft.AspNetCore.SignalR.Server, но jquery.signalr не появился в проекте
    – Alex
    29 апр 2017 в 19:03
  • подключил Microsoft.AspNet.SignalR.Core но также jquery.signalr не появился в проекте
    – Alex
    29 апр 2017 в 19:04

1 ответ 1

0

This (ASP.NET CORE) is a 1.0 product which means it is just the beginning and does not have all the functionality of ASP.NET 4.x stack. For example, features like SignalR and Web Pages will come later in the year..

https://blogs.msdn.microsoft.com/webdev/2016/06/27/announcing-asp-net-core-1-0/

2

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.