一個小demo。
webapi跨域問題,參見VS2019下開發和調用webapi
webapi
代碼:
[Route("api/[controller]/[action]")] [ApiController] public class ValuesController : ControllerBase { public string Index() { return "Hello Katty."; } [HttpGet("{x}")] public string Index1(string x) { return x + ",Hello Katty."; } }
blazor
program.cs:
1 var builder = WebAssemblyHostBuilder.CreateDefault(args); 2 builder.RootComponents.Add<App>("#app"); 3 builder.RootComponents.Add<HeadOutlet>("head::after"); 4 5 builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("http://localhost:5014/") }); 6 7 await builder.Build().RunAsync();
修改了第6行,僅修改了webapi服務器地址。這一行說明httpclient是作用域注入(這里相當於單例)。
index.razor:
1 @page "/" 2 @inject HttpClient Http 3 4 用戶名:<input @bind=u />密碼:<input @bind=p /><br /> 5 結果:@msg<br /> 6 <button @onclick="Sub">提交</button> 7 @code { 8 private string u=string.Empty; 9 private string p=string.Empty; 10 private string msg="提示"; 11 int c = 1; 12 13 private async void Sub() 14 { 15 msg=await Http.GetStringAsync($"/api/values/index1/{c}"); 16 c++; 17 StateHasChanged(); 18 } 19 }
第2行,注入。代碼里可以用Http表示單例的HttpClient。
第17行的StateHasChanged();用於強制刷新,此處強制刷新第5行處。
