Update to using System.Net.Http.Json (#20195)

This commit is contained in:
Pranav K 2020-03-26 10:13:23 -07:00 committed by GitHub
parent b0a95d05e0
commit cb6858fe31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 22 additions and 373 deletions

View File

@ -90,6 +90,7 @@ and are generated based on the last package release.
<LatestPackageReference Include="System.Diagnostics.EventLog" Version="$(SystemDiagnosticsEventLogPackageVersion)" /> <LatestPackageReference Include="System.Diagnostics.EventLog" Version="$(SystemDiagnosticsEventLogPackageVersion)" />
<LatestPackageReference Include="System.IO.Pipelines" Version="$(SystemIOPipelinesPackageVersion)" /> <LatestPackageReference Include="System.IO.Pipelines" Version="$(SystemIOPipelinesPackageVersion)" />
<LatestPackageReference Include="System.Net.Http" Version="$(SystemNetHttpPackageVersion)" /> <LatestPackageReference Include="System.Net.Http" Version="$(SystemNetHttpPackageVersion)" />
<LatestPackageReference Include="System.Net.Http.Json" Version="$(SystemNetHttpJsonPackageVersion)" />
<LatestPackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataPackageVersion)" /> <LatestPackageReference Include="System.Reflection.Metadata" Version="$(SystemReflectionMetadataPackageVersion)" />
<LatestPackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafePackageVersion)" /> <LatestPackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafePackageVersion)" />
<LatestPackageReference Include="System.Security.Cryptography.Cng" Version="$(SystemSecurityCryptographyCngPackageVersion)" /> <LatestPackageReference Include="System.Security.Cryptography.Cng" Version="$(SystemSecurityCryptographyCngPackageVersion)" />

View File

@ -7,7 +7,6 @@
<ItemGroup> <ItemGroup>
<ProjectReferenceProvider Include="Microsoft.Authentication.WebAssembly.Msal" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Authentication.Msal\src\Microsoft.Authentication.WebAssembly.Msal.csproj" /> <ProjectReferenceProvider Include="Microsoft.Authentication.WebAssembly.Msal" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Authentication.Msal\src\Microsoft.Authentication.WebAssembly.Msal.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Components.WebAssembly.Build" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Build\src\Microsoft.AspNetCore.Components.WebAssembly.Build.csproj" /> <ProjectReferenceProvider Include="Microsoft.AspNetCore.Components.WebAssembly.Build" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Build\src\Microsoft.AspNetCore.Components.WebAssembly.Build.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Blazor.HttpClient" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Http\src\Microsoft.AspNetCore.Blazor.HttpClient.csproj" />
<ProjectReferenceProvider Include="Microsoft.JSInterop.WebAssembly" ProjectPath="$(RepoRoot)src\Components\WebAssembly\JSInterop\src\Microsoft.JSInterop.WebAssembly.csproj" /> <ProjectReferenceProvider Include="Microsoft.JSInterop.WebAssembly" ProjectPath="$(RepoRoot)src\Components\WebAssembly\JSInterop\src\Microsoft.JSInterop.WebAssembly.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Components.WebAssembly.Server" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Server\src\Microsoft.AspNetCore.Components.WebAssembly.Server.csproj" /> <ProjectReferenceProvider Include="Microsoft.AspNetCore.Components.WebAssembly.Server" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Server\src\Microsoft.AspNetCore.Components.WebAssembly.Server.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Validation\src\Microsoft.AspNetCore.Components.DataAnnotations.Validation.csproj" /> <ProjectReferenceProvider Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" ProjectPath="$(RepoRoot)src\Components\WebAssembly\Validation\src\Microsoft.AspNetCore.Components.DataAnnotations.Validation.csproj" />

View File

@ -13,6 +13,10 @@
<Uri>https://github.com/dotnet/blazor</Uri> <Uri>https://github.com/dotnet/blazor</Uri>
<Sha>42941006ace24b5cb66a99ff52828a935f62ebcf</Sha> <Sha>42941006ace24b5cb66a99ff52828a935f62ebcf</Sha>
</Dependency> </Dependency>
<Dependency Name="System.Net.Http.Json" Version="3.2.0-preview3.20175.8">
<Uri>https://github.com/dotnet/corefx</Uri>
<Sha>6ab82925fc3ca30b3c7e6ba060d0d5bd5ae76b06</Sha>
</Dependency>
</ProductDependencies> </ProductDependencies>
<ToolsetDependencies> <ToolsetDependencies>
<Dependency Name="Microsoft.DotNet.GenAPI" Version="1.0.0-beta.20124.2"> <Dependency Name="Microsoft.DotNet.GenAPI" Version="1.0.0-beta.20124.2">

View File

@ -93,6 +93,7 @@
<SystemServiceProcessServiceControllerPackageVersion>4.7.0</SystemServiceProcessServiceControllerPackageVersion> <SystemServiceProcessServiceControllerPackageVersion>4.7.0</SystemServiceProcessServiceControllerPackageVersion>
<SystemTextEncodingsWebPackageVersion>4.7.0</SystemTextEncodingsWebPackageVersion> <SystemTextEncodingsWebPackageVersion>4.7.0</SystemTextEncodingsWebPackageVersion>
<SystemTextJsonPackageVersion>4.7.1</SystemTextJsonPackageVersion> <SystemTextJsonPackageVersion>4.7.1</SystemTextJsonPackageVersion>
<SystemNetHttpJsonPackageVersion>3.2.0-preview3.20175.8</SystemNetHttpJsonPackageVersion>
<SystemThreadingChannelsPackageVersion>4.7.0</SystemThreadingChannelsPackageVersion> <SystemThreadingChannelsPackageVersion>4.7.0</SystemThreadingChannelsPackageVersion>
<SystemWindowsExtensionsPackageVersion>4.7.0</SystemWindowsExtensionsPackageVersion> <SystemWindowsExtensionsPackageVersion>4.7.0</SystemWindowsExtensionsPackageVersion>
<!-- Only listed explicitly to workaround https://github.com/dotnet/cli/issues/10528 --> <!-- Only listed explicitly to workaround https://github.com/dotnet/cli/issues/10528 -->

View File

@ -41,8 +41,6 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Build
fewer assemblies from the server, and during publishing, illink would remove all the fewer assemblies from the server, and during publishing, illink would remove all the
uncalled implementation code from mscorlib.dll anyway. uncalled implementation code from mscorlib.dll anyway.
*/ */
"Microsoft.AspNetCore.Blazor.HttpClient.dll",
"Microsoft.AspNetCore.Blazor.HttpClient.pdb",
"Microsoft.AspNetCore.Components.dll", "Microsoft.AspNetCore.Components.dll",
"Microsoft.AspNetCore.Components.Forms.dll", "Microsoft.AspNetCore.Components.Forms.dll",
"Microsoft.AspNetCore.Components.Web.dll", "Microsoft.AspNetCore.Components.Web.dll",
@ -81,6 +79,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Build
"System.IO.Compression.FileSystem.dll", "System.IO.Compression.FileSystem.dll",
"System.Memory.dll", "System.Memory.dll",
"System.Net.Http.dll", "System.Net.Http.dll",
"System.Net.Http.Json.dll",
"System.Numerics.dll", "System.Numerics.dll",
"System.Numerics.Vectors.dll", "System.Numerics.Vectors.dll",
"System.Runtime.CompilerServices.Unsafe.dll", "System.Runtime.CompilerServices.Unsafe.dll",

View File

@ -1,121 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Components
{
/// <summary>
/// Extension methods for working with JSON APIs.
/// </summary>
public static class HttpClientJsonExtensions
{
/// <summary>
/// Sends a GET request to the specified URI, and parses the JSON response body
/// to create an object of the generic type.
/// </summary>
/// <typeparam name="T">A type into which the response body can be JSON-deserialized.</typeparam>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <returns>The response parsed as an object of the generic type.</returns>
public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri)
{
var stringContent = await httpClient.GetStringAsync(requestUri);
return JsonSerializer.Deserialize<T>(stringContent, JsonSerializerOptionsProvider.Options);
}
/// <summary>
/// Sends a POST request to the specified URI, including the specified <paramref name="content"/>
/// in JSON-encoded format, and parses the JSON response body to create an object of the generic type.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <param name="content">Content for the request body. This will be JSON-encoded and sent as a string.</param>
/// <returns>The response parsed as an object of the generic type.</returns>
public static Task PostJsonAsync(this HttpClient httpClient, string requestUri, object content)
=> httpClient.SendJsonAsync(HttpMethod.Post, requestUri, content);
/// <summary>
/// Sends a POST request to the specified URI, including the specified <paramref name="content"/>
/// in JSON-encoded format, and parses the JSON response body to create an object of the generic type.
/// </summary>
/// <typeparam name="T">A type into which the response body can be JSON-deserialized.</typeparam>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <param name="content">Content for the request body. This will be JSON-encoded and sent as a string.</param>
/// <returns>The response parsed as an object of the generic type.</returns>
public static Task<T> PostJsonAsync<T>(this HttpClient httpClient, string requestUri, object content)
=> httpClient.SendJsonAsync<T>(HttpMethod.Post, requestUri, content);
/// <summary>
/// Sends a PUT request to the specified URI, including the specified <paramref name="content"/>
/// in JSON-encoded format.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <param name="content">Content for the request body. This will be JSON-encoded and sent as a string.</param>
public static Task PutJsonAsync(this HttpClient httpClient, string requestUri, object content)
=> httpClient.SendJsonAsync(HttpMethod.Put, requestUri, content);
/// <summary>
/// Sends a PUT request to the specified URI, including the specified <paramref name="content"/>
/// in JSON-encoded format, and parses the JSON response body to create an object of the generic type.
/// </summary>
/// <typeparam name="T">A type into which the response body can be JSON-deserialized.</typeparam>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <param name="content">Content for the request body. This will be JSON-encoded and sent as a string.</param>
/// <returns>The response parsed as an object of the generic type.</returns>
public static Task<T> PutJsonAsync<T>(this HttpClient httpClient, string requestUri, object content)
=> httpClient.SendJsonAsync<T>(HttpMethod.Put, requestUri, content);
/// <summary>
/// Sends an HTTP request to the specified URI, including the specified <paramref name="content"/>
/// in JSON-encoded format.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="method">The HTTP method.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <param name="content">Content for the request body. This will be JSON-encoded and sent as a string.</param>
public static Task SendJsonAsync(this HttpClient httpClient, HttpMethod method, string requestUri, object content)
=> httpClient.SendJsonAsync<IgnoreResponse>(method, requestUri, content);
/// <summary>
/// Sends an HTTP request to the specified URI, including the specified <paramref name="content"/>
/// in JSON-encoded format, and parses the JSON response body to create an object of the generic type.
/// </summary>
/// <typeparam name="T">A type into which the response body can be JSON-deserialized.</typeparam>
/// <param name="httpClient">The <see cref="HttpClient"/>.</param>
/// <param name="method">The HTTP method.</param>
/// <param name="requestUri">The URI that the request will be sent to.</param>
/// <param name="content">Content for the request body. This will be JSON-encoded and sent as a string.</param>
/// <returns>The response parsed as an object of the generic type.</returns>
public static async Task<T> SendJsonAsync<T>(this HttpClient httpClient, HttpMethod method, string requestUri, object content)
{
var requestJson = JsonSerializer.Serialize(content, JsonSerializerOptionsProvider.Options);
var response = await httpClient.SendAsync(new HttpRequestMessage(method, requestUri)
{
Content = new StringContent(requestJson, Encoding.UTF8, "application/json")
});
// Make sure the call was successful before we
// attempt to process the response content
response.EnsureSuccessStatusCode();
if (typeof(T) == typeof(IgnoreResponse))
{
return default;
}
else
{
var stringContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(stringContent, JsonSerializerOptionsProvider.Options);
}
}
class IgnoreResponse { }
}
}

View File

@ -1,18 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Description>Provides experimental support for using System.Text.Json with HttpClient. Intended for use with Blazor running under WebAssembly.</Description>
<IsShippingPackage>true</IsShippingPackage>
<HasReferenceAssembly>false</HasReferenceAssembly>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Shared\src\JsonSerializerOptionsProvider.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Text.Json" />
</ItemGroup>
</Project>

View File

@ -1,209 +0,0 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Components.Test
{
public class HttpClientJsonExtensionsTest
{
private readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
};
const string TestUri = "http://example.com/some/uri";
[Fact]
public async Task GetJson_Success()
{
// Arrange
var httpClient = new HttpClient(new TestHttpMessageHandler(req =>
{
Assert.Equal(TestUri, req.RequestUri.AbsoluteUri);
return Task.FromResult(CreateJsonResponse(HttpStatusCode.OK, new Person
{
Name = "Abc",
Age = 123
}));
}));
// Act
var result = await httpClient.GetJsonAsync<Person>(TestUri);
// Assert
Assert.Equal("Abc", result.Name);
Assert.Equal(123, result.Age);
}
[Fact]
public async Task GetJson_Failure()
{
// Arrange
var httpClient = new HttpClient(new TestHttpMessageHandler(req =>
{
Assert.Equal(TestUri, req.RequestUri.AbsoluteUri);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound));
}));
// Act/Assert
var ex = await Assert.ThrowsAsync<HttpRequestException>(
() => httpClient.GetJsonAsync<Person>(TestUri));
Assert.Contains("404 (Not Found)", ex.Message);
}
[Theory]
[InlineData("Put")]
[InlineData("Post")]
[InlineData("Patch")]
[InlineData("Delete")]
[InlineData("MyArtificialMethod")]
public async Task SendJson_Success(string httpMethodString)
{
var httpMethod = new HttpMethod(httpMethodString);
var requestContent = new { MyProp = true, OtherProp = "Hello" };
// Arrange
var httpClient = new HttpClient(new TestHttpMessageHandler(async req =>
{
Assert.Equal(httpMethod, req.Method);
Assert.Equal(TestUri, req.RequestUri.AbsoluteUri);
Assert.Equal(JsonSerializer.Serialize(requestContent, _jsonSerializerOptions), await ((StringContent)req.Content).ReadAsStringAsync());
return CreateJsonResponse(HttpStatusCode.OK, new Person
{
Name = "Abc",
Age = 123
});
}));
// Act
var result = await Send(httpClient, httpMethodString, requestContent);
// Assert
Assert.Equal("Abc", result.Name);
Assert.Equal(123, result.Age);
}
[Fact]
public async Task ReadAsJsonAsync_ReadsCamelCasedJson()
{
var input = "{\"name\": \"TestPerson\", \"age\": 23 }";
// Arrange
var httpClient = new HttpClient(new TestHttpMessageHandler(req =>
{
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(input)
});
}));
// Act
var result = await httpClient.GetJsonAsync<Person>(TestUri);
// Assert
Assert.Equal("TestPerson", result.Name);
Assert.Equal(23, result.Age);
}
[Fact]
public async Task ReadAsJsonAsync_ReadsPascalCasedJson()
{
var input = "{\"Name\": \"TestPerson\", \"Age\": 23 }";
// Arrange
var httpClient = new HttpClient(new TestHttpMessageHandler(req =>
{
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(input)
});
}));
// Act
var result = await httpClient.GetJsonAsync<Person>(TestUri);
// Assert
Assert.Equal("TestPerson", result.Name);
Assert.Equal(23, result.Age);
}
[Theory]
[InlineData("Put")]
[InlineData("Post")]
[InlineData("Patch")]
[InlineData("Delete")]
[InlineData("MyArtificialMethod")]
public async Task SendJson_Failure(string httpMethodString)
{
var httpMethod = new HttpMethod(httpMethodString);
var requestContent = new { MyProp = true, OtherProp = "Hello" };
// Arrange
var httpClient = new HttpClient(new TestHttpMessageHandler(async req =>
{
Assert.Equal(httpMethod, req.Method);
Assert.Equal(TestUri, req.RequestUri.AbsoluteUri);
Assert.Equal(JsonSerializer.Serialize(requestContent, _jsonSerializerOptions), await ((StringContent)req.Content).ReadAsStringAsync());
return new HttpResponseMessage(HttpStatusCode.BadGateway);
}));
// Act/Assert
var ex = await Assert.ThrowsAsync<HttpRequestException>(
() => Send(httpClient, httpMethodString, requestContent));
Assert.Contains("502 (Bad Gateway)", ex.Message);
}
HttpResponseMessage CreateJsonResponse(HttpStatusCode statusCode, object content)
{
return new HttpResponseMessage(statusCode)
{
Content = new StringContent(JsonSerializer.Serialize(content, _jsonSerializerOptions))
};
}
Task<Person> Send(HttpClient httpClient, string httpMethodString, object requestContent)
{
// For methods with convenience overloads, show those overloads work
switch (httpMethodString)
{
case "post":
return httpClient.PostJsonAsync<Person>(TestUri, requestContent);
case "put":
return httpClient.PutJsonAsync<Person>(TestUri, requestContent);
default:
return httpClient.SendJsonAsync<Person>(new HttpMethod(httpMethodString), TestUri, requestContent);
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class TestHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, Task<HttpResponseMessage>> _sendDelegate;
public TestHttpMessageHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> sendDelegate)
{
_sendDelegate = sendDelegate;
}
protected override void Dispose(bool disposing)
=> base.Dispose(disposing);
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
=> _sendDelegate(request);
}
}
}

View File

@ -1,11 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>$(DefaultNetCoreTargetFramework)</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Blazor.HttpClient" />
</ItemGroup>
</Project>

View File

@ -52,7 +52,7 @@ else
protected override async Task OnParametersSetAsync() protected override async Task OnParametersSetAsync()
{ {
startDate = StartDate.GetValueOrDefault(DateTime.Now); startDate = StartDate.GetValueOrDefault(DateTime.Now);
forecasts = await Http.GetJsonAsync<WeatherForecast[]>( forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>(
$"sample-data/weather.json?date={startDate.ToString("yyyy-MM-dd")}"); $"sample-data/weather.json?date={startDate.ToString("yyyy-MM-dd")}");
// Because StandaloneApp doesn't really have a server endpoint to get dynamic data from, // Because StandaloneApp doesn't really have a server endpoint to get dynamic data from,

View File

@ -8,7 +8,7 @@
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.AspNetCore.Components.WebAssembly" /> <Reference Include="Microsoft.AspNetCore.Components.WebAssembly" />
<Reference Include="Microsoft.AspNetCore.Blazor.HttpClient" /> <Reference Include="System.Net.Http.Json" />
</ItemGroup> </ItemGroup>
<!-- A bit of msbuild magic to support reference resolver tests --> <!-- A bit of msbuild magic to support reference resolver tests -->

View File

@ -1,4 +1,5 @@
@using System.Net.Http @using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web @using Microsoft.AspNetCore.Components.Web
@using StandaloneApp @using StandaloneApp

View File

@ -50,7 +50,7 @@ else
if (tokenResult.TryGetToken(out var token)) if (tokenResult.TryGetToken(out var token))
{ {
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Value}"); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Value}");
forecasts = await httpClient.GetJsonAsync<WeatherForecast[]>("WeatherForecast"); forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
} }
else else
{ {

View File

@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.AspNetCore.Blazor.HttpClient" /> <Reference Include="System.Net.Http.Json" />
<Reference Include="Microsoft.AspNetCore.Components.WebAssembly" /> <Reference Include="Microsoft.AspNetCore.Components.WebAssembly" />
<Reference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" /> <Reference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" />
</ItemGroup> </ItemGroup>

View File

@ -1,4 +1,5 @@
@using System.Net.Http @using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication @using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Forms

View File

@ -4,6 +4,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Claims; using System.Security.Claims;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
@ -25,7 +26,7 @@ namespace BasicTestApp.AuthTest
public override async Task<AuthenticationState> GetAuthenticationStateAsync() public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{ {
var uri = new Uri(_httpClient.BaseAddress, "/subdir/api/User"); var uri = new Uri(_httpClient.BaseAddress, "/subdir/api/User");
var data = await _httpClient.GetJsonAsync<ClientSideAuthenticationStateData>(uri.AbsoluteUri); var data = await _httpClient.GetFromJsonAsync<ClientSideAuthenticationStateData>(uri.AbsoluteUri);
ClaimsIdentity identity; ClaimsIdentity identity;
if (data.IsAuthenticated) if (data.IsAuthenticated)
{ {

View File

@ -14,8 +14,8 @@
<ItemGroup> <ItemGroup>
<Reference Include="System.ComponentModel" /> <Reference Include="System.ComponentModel" />
<Reference Include="System.Net.Http.Json" />
<Reference Include="Microsoft.AspNetCore.Components.WebAssembly" /> <Reference Include="Microsoft.AspNetCore.Components.WebAssembly" />
<Reference Include="Microsoft.AspNetCore.Blazor.HttpClient" />
<Reference Include="Microsoft.AspNetCore.Components.Authorization" /> <Reference Include="Microsoft.AspNetCore.Components.Authorization" />
<Reference Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" /> <Reference Include="Microsoft.AspNetCore.Components.DataAnnotations.Validation" />
</ItemGroup> </ItemGroup>

View File

@ -12,9 +12,9 @@
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="${MicrosoftAspNetCoreComponentsWebAssemblyPackageVersion}" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="${MicrosoftAspNetCoreComponentsWebAssemblyPackageVersion}" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="${MicrosoftAspNetCoreComponentsWebAssemblyBuildPackageVersion}" PrivateAssets="all" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="${MicrosoftAspNetCoreComponentsWebAssemblyBuildPackageVersion}" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="${MicrosoftAspNetCoreComponentsWebAssemblyDevServerPackageVersion}" PrivateAssets="all" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="${MicrosoftAspNetCoreComponentsWebAssemblyDevServerPackageVersion}" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="${MicrosoftAspNetCoreBlazorHttpClientPackageVersion}" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="${MicrosoftAspNetCoreComponentsWebAssemblyAuthenticationPackageVersion}" Condition="'$(IndividualLocalAuth)' == 'true'" /> <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="${MicrosoftAspNetCoreComponentsWebAssemblyAuthenticationPackageVersion}" Condition="'$(IndividualLocalAuth)' == 'true'" />
<PackageReference Include="Microsoft.Authentication.WebAssembly.Msal" Version="${MicrosoftAuthenticationWebAssemblyMsalPackageVersion}" Condition="'$(OrganizationalAuth)' == 'true' OR '$(IndividualB2CAuth)' == 'true'" /> <PackageReference Include="Microsoft.Authentication.WebAssembly.Msal" Version="${MicrosoftAuthenticationWebAssemblyMsalPackageVersion}" Condition="'$(OrganizationalAuth)' == 'true' OR '$(IndividualB2CAuth)' == 'true'" />
<PackageReference Include="System.Net.Http.Json" Version="${SystemNetHttpJsonPackageVersion}" />
</ItemGroup> </ItemGroup>
<!--#if Hosted --> <!--#if Hosted -->

View File

@ -29,6 +29,7 @@
MicrosoftEntityFrameworkCoreSqlServerPackageVersion=$(MicrosoftEntityFrameworkCoreSqlServerPackageVersion); MicrosoftEntityFrameworkCoreSqlServerPackageVersion=$(MicrosoftEntityFrameworkCoreSqlServerPackageVersion);
MicrosoftEntityFrameworkCoreSqlitePackageVersion=$(MicrosoftEntityFrameworkCoreSqlitePackageVersion); MicrosoftEntityFrameworkCoreSqlitePackageVersion=$(MicrosoftEntityFrameworkCoreSqlitePackageVersion);
MicrosoftEntityFrameworkCoreToolsPackageVersion=$(MicrosoftEntityFrameworkCoreToolsPackageVersion); MicrosoftEntityFrameworkCoreToolsPackageVersion=$(MicrosoftEntityFrameworkCoreToolsPackageVersion);
SystemNetHttpJsonPackageVersion=$(SystemNetHttpJsonPackageVersion)
</GeneratedContentProperties> </GeneratedContentProperties>
</PropertyGroup> </PropertyGroup>
@ -37,7 +38,6 @@
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)WebAssembly\src\Microsoft.AspNetCore.Components.WebAssembly.csproj" /> <PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)WebAssembly\src\Microsoft.AspNetCore.Components.WebAssembly.csproj" />
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Build\src\Microsoft.AspNetCore.Components.WebAssembly.Build.csproj" /> <PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Build\src\Microsoft.AspNetCore.Components.WebAssembly.Build.csproj" />
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)DevServer\src\Microsoft.AspNetCore.Components.WebAssembly.DevServer.csproj" /> <PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)DevServer\src\Microsoft.AspNetCore.Components.WebAssembly.DevServer.csproj" />
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Http\src\Microsoft.AspNetCore.Blazor.HttpClient.csproj" />
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Server\src\Microsoft.AspNetCore.Components.WebAssembly.Server.csproj" /> <PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Server\src\Microsoft.AspNetCore.Components.WebAssembly.Server.csproj" />
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)WebAssembly.Authentication\src\Microsoft.AspNetCore.Components.WebAssembly.Authentication.csproj" /> <PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)WebAssembly.Authentication\src\Microsoft.AspNetCore.Components.WebAssembly.Authentication.csproj" />
<PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Authentication.Msal\src\Microsoft.Authentication.WebAssembly.Msal.csproj" /> <PackageVersionVariableReference Include="$(ComponentsWebAssemblyProjectsRoot)Authentication.Msal\src\Microsoft.Authentication.WebAssembly.Msal.csproj" />

View File

@ -63,7 +63,7 @@ else
if (tokenResult.TryGetToken(out var token)) if (tokenResult.TryGetToken(out var token))
{ {
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Value}"); httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Value}");
forecasts = await httpClient.GetJsonAsync<WeatherForecast[]>("WeatherForecast"); forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
} }
else else
{ {
@ -71,10 +71,10 @@ else
} }
#else #else
forecasts = await Http.GetJsonAsync<WeatherForecast[]>("WeatherForecast"); forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
#endif*@ #endif*@
#else #else
forecasts = await Http.GetJsonAsync<WeatherForecast[]>("sample-data/weather.json"); forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
#endif*@ #endif*@
} }

View File

@ -1,4 +1,5 @@
@using System.Net.Http @using System.Net.Http
@using System.Net.Http.Json
@*#if (!NoAuth) @*#if (!NoAuth)
@using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Authorization
#endif*@ #endif*@