在 appsetting.json 中配置基础连接 Url
"backendUrl": "https://localhost:5901"
封装客户端访问类
using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace frontend { public class PizzaClient { private readonly JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; private readonly HttpClient client; private readonly ILogger<PizzaClient> _logger; public PizzaClient(HttpClient client, ILogger<PizzaClient> logger) { this.client = client; this._logger = logger; } public async Task<PizzaInfo[]> GetPizzasAsync() { try { var responseMessage = await this.client.GetAsync("/pizzainfo"); if(responseMessage!=null) { var stream = await responseMessage.Content.ReadAsStreamAsync(); return await JsonSerializer.DeserializeAsync<PizzaInfo[]>(stream, options); } } catch(HttpRequestException ex) { _logger.LogError(ex.Message); throw; } return new PizzaInfo[] {}; } } }
注册服务类 PizzaClient ,并设置基础 Url 地址
public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddHttpClient<PizzaClient>(client => { var baseAddress = new Uri(Configuration.GetValue<string>("backendUrl")); client.BaseAddress = baseAddress; }); }
UI消费
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace frontend.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public PizzaInfo[] Pizzas { get; set; } public string ErrorMessage {get;set;} public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public async Task OnGet([FromServices]PizzaClient client) { Pizzas = await client.GetPizzasAsync(); if(Pizzas.Count()==0) ErrorMessage="We must be sold out. Try again tomorrow."; else ErrorMessage = string.Empty; } } }
标签:Razor,System,client,API,PizzaClient,using,logger,public,客户端 From: https://www.cnblogs.com/friend/p/16717951.html