ASP.NET Core Blazor WebAssembly でランダムにわんこを表示する
Dog API を使って Blazor でランダムにわんこを表示させます。
環境
Microsoft Visual Studio Community 2019 Version 16.9.3
プロジェクト作成
BlazorDog
という名前で新しい Blazor WebAssembly プロジェクトを作成します。
[ASP.NET Core でホストされた] を選択しておきます。
Dog クラス作成
BlazorDog.Shared
プロジェクト直下に Dog
クラスを追加します。
namespace BlazorDog.Shared { public class Dog { public string Message { get; set; } public string Status { get; set; } } }
IHttpClientFactory の登録
BlazorDog.Server
プロジェクトの Startup.cs
を以下のように書き換えて IHttpClientFactory を登録します
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace BlazorDog.Server { 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. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); // 追加 services.AddControllersWithViews(); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); // 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.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapFallbackToFile("index.html"); }); } } }
DogController 作成
BlazorDog.Server
プロジェクトの Controllers
フォルダー配下に DogController
コントローラーを追加します。
using BlazorDog.Shared; using Microsoft.AspNetCore.Mvc; using System.Net.Http; using System.Threading.Tasks; using System.Text.Json; namespace BlazorDog.Server.Controllers { [Route("api/[controller]")] [ApiController] public class DogController : ControllerBase { private readonly IHttpClientFactory clientFactory; public DogController(IHttpClientFactory clientFactory) { this.clientFactory = clientFactory; } [HttpGet] public async Task<ActionResult<Dog>> GetDogAsync() { var request = new HttpRequestMessage(HttpMethod.Get, "https://dog.ceo/api/breeds/image/random"); var client = clientFactory.CreateClient(); var response = await client.SendAsync(request); var responseString = await response.Content.ReadAsStringAsync(); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; Dog dog = JsonSerializer.Deserialize<Dog>(responseString, options); return Ok(dog); } } }
Index ページの更新
BlazorDog.Client
プロジェクトの Pages
フォルダー配下の Index.razor
を以下のように書き換えます。
@page "/" @using BlazorDog.Shared @inject HttpClient Http @if (dog == null) { <p><em>Loading...</em></p> } else { <img src="@dog.Message" /> } @code { private Dog dog; protected override async Task OnInitializedAsync() { dog = await Http.GetFromJsonAsync<Dog>("api/dog"); } }
結果
実行するとこんな感じになりました。