创建并在.NET MAUIAPP

问题描述 投票:0回答:4
我们在.NET MAUI应用程序中创建/使用

HttpClient

,就像我们在Web或API应用程序中相同的方式吗?具体来说,我将我的
HttpClient
添加到我的应用中
Program.cs
使用
IHttpFactory
-参见下文:

builder.Services.AddHttpClient("NamedClient1", config => { var url = currentState == "production" ? "https://my-production-url" : "https://sandbox-url"; config.BaseAddress = new Uri(url); });
我以.net Maui了解这个想法是为了标准化我们处理事物的方式。当我尝试在.NET MAUI应用中添加该行

builder.Services

时,Intellisense并不建议
AddHttpClient

xamarin xamarin.forms maui .net-maui
4个回答
6
投票
builder.Services.AddScoped(sp => new HttpClient { });

移动开发中的HTTPCLEINT与Web有点不同。这些设备可以很好地处理HTTPCLIENT本身,我们不必担心通过使用Nuget软件包(Microsoft.extensions.http)正确处理它。因此,您可以改用AddSingleton,甚至可以使用HTTPClient的静态读取。 .NET MAUI团队确保以这种方式配置HTTPCLIENT类。
Microsoft的source:

5
投票
.NET MAUI模板将HTTPCLIENT类映射到用于每个平台本机网络堆栈的代码。这使应用程序能够利用平台特定的网络配置和优化功能

我正在使用.NET 8并开发一个.Net Maui Blazor Hybrid应用程序,该应用与我的ASP.NETAPI
连接

我们的法案叔叔建议(并且效果很好)是创建API服务:

创建您的服务课:

0
投票
public class APIService : IAPIService { HttpClient _httpClient; JsonSerializerOptions _jsonSerializerOptions; Uri _baseURI; public APIService() { _httpClient = new HttpClient(); _jsonSerializerOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, }; _baseURI = new Uri("https://localhost:7148"); } public async Task<bool> POSTCredentialsAsync(LoginCommand command) { var response = await _httpClient.PostAsJsonAsync(_baseURI + "/login", command); if (response.IsSuccessStatusCode) { return true; } return false; } public async Task<bool> POSTRegistrationAsync(RegisterMarket command) { var response = await _httpClient.PostAsJsonAsync(_baseURI + "/register", command); if (response.IsSuccessStatusCode) { return true; } return false; } }

上面的

界面(对于页面中的依赖注入,Glazor Pages使用@Inject):

internal interface IAPIService { public Task<bool> POSTCredentialsAsync(LoginCommand command); public Task<bool> POSTRegistrationAsync(RegisterMarket command); }

lastly,在Mauiprogram.cs
builder.Services.AddScoped<IAPIService, APIService>();

在我的应用程序中真的很好

您可以处理另一个源文件中的响应 希望它有帮助 预先感谢

Microsoftoficial参考:
https://learn.microsoft.com/en-us/dotnet/maui/data-cloud/rest/rest?view = net-maui-9.0


-temperature.xaml.cs

using System.Diagnostics.Metrics; using System.Text.Json; using System.Xml.Serialization; namespace TPMaui3.Views; public partial class vTemperature : ContentPage { public vTemperature() { InitializeComponent(); } private void AfficheTemperature(object sender, EventArgs e) { LireTemperature(); } private async void LireTemperature() { Uri uri = new("http://meteorestsrvmobile.lab3il.fr/RestServiceMeteo.svc/xml/1"); try { HttpClient client = new(); HttpResponseMessage response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { String content = await response.Content.ReadAsStringAsync(); content = content.Substring(content.IndexOf("<XMLDataResult>") + 15); content = content.Substring(0, content.IndexOf("</XMLDataResult>")); lbTemp.Text = content + " °C"; } } catch (Exception ex) { await this.DisplayAlert("Error", ex.Message, "OK"); } } }

Vmeteo.xaml <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="TPMaui3.Views.vMeteo" Title="Météo" > <VerticalStackLayout Spacing="20" Margin="10" > <Label Text="Météo" x:Name="lbMeteo" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Primary}" /> <Label Text="?" x:Name="lbTemperature" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> <Label Text="?" x:Name="lbPression" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> <Label Text="?" x:Name="lbHumidite" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> <Label Text="?" x:Name="lbPrecipitationJour" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> <Label Text="?" x:Name="lbTemperatureRessentie" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> <Label Text="?" x:Name="lbVentDirection" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> <Label Text="?" x:Name="lbVentVitesse" VerticalOptions="Center" HorizontalOptions="Center" FontSize="Medium" TextColor="{StaticResource Secondary}" /> </VerticalStackLayout> </ContentPage>


-7
投票

using System.Diagnostics.Metrics; using System.Text.Json; using TPMaui3.Models; namespace TPMaui3.Views; public partial class vMeteo : ContentPage { public vMeteo() { InitializeComponent(); Meteo(); } private async void Meteo() { Uri uri = new("http://meteorestsrvmobile.lab3il.fr/RestServiceMeteo.svc/jsontmps"); try { HttpClient client = new(); HttpResponseMessage response = await client.GetAsync(uri); JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions(); if (response.IsSuccessStatusCode) { var result = await response.Content.ReadAsStringAsync(); result = result.Replace("{\"JSONDataTmpsResult\":", ""); result = result.Replace("}}", "}"); var vMeteo = Newtonsoft.Json.JsonConvert.DeserializeObject<CMeteo>(result); lbMeteo.Text = "Relevé à " + vMeteo.DateReleve.ToString(); lbTemperature.Text = "Temp: " + vMeteo.Temperature.ToString() + " °C"; lbHumidite.Text = "Hum: " + vMeteo.Humidite.ToString() + " %"; lbPression.Text = "Pres: " + vMeteo.Pression.ToString() + " hPa"; lbTemperatureRessentie.Text = "TR: " + vMeteo.TemperatureRessentie.ToString() + " °C"; lbPrecipitationJour.Text = "PrecJ: " + vMeteo.PrecipitationJour.ToString() + " mm"; lbVentVitesse.Text = "Vit: " + vMeteo.VentVitesse.ToString() + " m/s"; lbVentDirection.Text = "Vent: " + vMeteo.VentDirection.ToString(); } } catch (Exception ex) { await this.DisplayAlert("Error", ex.Message, "OK"); } } }

Cmeteo.cs

using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Text.Json; using System.Threading.Tasks; using TPMaui3.Views; namespace TPMaui3.Models; internal class CMeteo { public CMeteo() { } public string DateReleve { get; set; } public string Temperature { get; set; } public string Pression { get; set; } public string Humidite { get; set; } public string PrecipitationJour { get; set; } public string TemperatureRessentie { get; set; } public string VentDirection { get; set; } public string VentVitesse { get; set; } }

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.