かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

サーバーサイド Blazor で Azure SignalR サービスを使う

サーバーサイド Blazor ってサーバーとブラウザーの間は SignalR 使って接続するんですってね。 SignalR 側がスケールするために Azure SignalR Service を使うこともできる機能が Azure SignalR SDK v1.1.0 (preview) で追加されてるみたいです。

devblogs.microsoft.com

ふむ、サーバーがスケールした場合には再接続時にも同じサーバーにアクセスできないといけないから、Blazor で使う場合には ServerStickerMode は Required か Preferred にしておかないと再接続時に不幸が起きそうな気がする。

なので、Startup.cs の ConfigureServices あたりに以下のように AddSignalR と AddAzureSignalR を追加することになるはずかな?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SignalRSDKSample.Data;

namespace SignalRSDKSample
{
    public class Startup
    {
        private readonly IWebHostEnvironment _env;

        public Startup(IWebHostEnvironment env)
        {
            _env = env ?? throw new ArgumentNullException(nameof(env));
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            if (_env.IsProduction())
            {
                services.AddSignalR().AddAzureSignalR(options => options.ServerStickyMode = Microsoft.Azure.SignalR.ServerStickyMode.Required);
            }
            services.AddSingleton<WeatherForecastService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            if (_env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // 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.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

そして、Azure Web App の構成の Azure:SignalR:ConnectionString に Azure SignalR Service の Keys から接続文字列をとってきて張り付けて完成。

f:id:okazuki:20190611171902p:plain

.NET Core 3.0 は、まだプレビューなので Web App に対して Self-Contained でデプロイして動かしてみると、ちゃんと Azure SignalR Service の方に繋ぎにいっているログがコンソールに出てました。

f:id:okazuki:20190611171432p:plain

まとめ

便利。