Skip to content

Commit 49c91ad

Browse files
authored
Merge pull request #17869 from dotnet/master
2 parents d5d45d8 + 1584f40 commit 49c91ad

4 files changed

Lines changed: 57 additions & 14 deletions

File tree

aspnetcore/blazor/call-web-api.md

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
---
2-
title: Call a web API from ASP.NET Core Blazor
2+
title: Call a web API from ASP.NET Core Blazor WebAssembly
33
author: guardrex
4-
description: Learn how to call a web API from a Blazor app using JSON helpers, including making cross-origin resource sharing (CORS) requests.
4+
description: Learn how to call a web API from a Blazor WebAssembly app using JSON helpers, including making cross-origin resource sharing (CORS) requests.
55
monikerRange: '>= aspnetcore-3.1'
66
ms.author: riande
77
ms.custom: mvc
8-
ms.date: 01/22/2020
8+
ms.date: 04/16/2020
99
no-loc: [Blazor, SignalR]
1010
uid: blazor/call-web-api
1111
---
@@ -28,9 +28,19 @@ See the following components in the *BlazorWebAssemblySample* sample app:
2828

2929
## Packages
3030

31-
Reference the *experimental* [Microsoft.AspNetCore.Blazor.HttpClient](https://www.nuget.org/packages/Microsoft.AspNetCore.Blazor.HttpClient/) NuGet package in the project file. `Microsoft.AspNetCore.Blazor.HttpClient` is based on `HttpClient` and [System.Text.Json](https://www.nuget.org/packages/System.Text.Json/).
31+
Reference the [System.Net.Http.Json](https://www.nuget.org/packages/System.Net.Http.Json/) NuGet package in the project file.
3232

33-
To use a stable API, use the [Microsoft.AspNet.WebApi.Client](https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/) package, which uses [Newtonsoft.Json](https://www.nuget.org/packages/Newtonsoft.Json/)/[Json.NET](https://www.newtonsoft.com/json/help/html/Introduction.htm). Using the stable API in `Microsoft.AspNet.WebApi.Client` doesn't provide the JSON helpers described in this topic, which are unique to the experimental `Microsoft.AspNetCore.Blazor.HttpClient` package.
33+
## Add the HttpClient service
34+
35+
In `Program.Main`, add an `HttpClient` service if it doesn't already exist:
36+
37+
```csharp
38+
builder.Services.AddSingleton(
39+
new HttpClient
40+
{
41+
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
42+
});
43+
```
3444

3545
## HttpClient and JSON helpers
3646

@@ -64,7 +74,7 @@ private class TodoItem
6474

6575
JSON helper methods send requests to a URI (a web API in the following examples) and process the response:
6676

67-
* `GetJsonAsync` – Sends an HTTP GET request and parses the JSON response body to create an object.
77+
* `GetFromJsonAsync` – Sends an HTTP GET request and parses the JSON response body to create an object.
6878

6979
In the following code, the `_todoItems` are displayed by the component. The `GetTodoItems` method is triggered when the component is finished rendering ([OnInitializedAsync](xref:blazor/lifecycle#component-initialization-methods)). See the sample app for a complete example.
7080

@@ -76,11 +86,11 @@ JSON helper methods send requests to a URI (a web API in the following examples)
7686
private TodoItem[] _todoItems;
7787
7888
protected override async Task OnInitializedAsync() =>
79-
_todoItems = await Http.GetJsonAsync<TodoItem[]>("api/TodoItems");
89+
_todoItems = await Http.GetFromJsonAsync<TodoItem[]>("api/TodoItems");
8090
}
8191
```
8292

83-
* `PostJsonAsync` &ndash; Sends an HTTP POST request, including JSON-encoded content, and parses the JSON response body to create an object.
93+
* `PostAsJsonAsync` &ndash; Sends an HTTP POST request, including JSON-encoded content, and parses the JSON response body to create an object.
8494

8595
In the following code, `_newItemName` is provided by a bound element of the component. The `AddItem` method is triggered by selecting a `<button>` element. See the sample app for a complete example.
8696

@@ -97,12 +107,14 @@ JSON helper methods send requests to a URI (a web API in the following examples)
97107
private async Task AddItem()
98108
{
99109
var addItem = new TodoItem { Name = _newItemName, IsComplete = false };
100-
await Http.PostJsonAsync("api/TodoItems", addItem);
110+
await Http.PostAsJsonAsync("api/TodoItems", addItem);
101111
}
102112
}
103113
```
114+
115+
Calls to `PostAsJsonAsync` return an <xref:System.Net.Http.HttpResponseMessage>.
104116

105-
* `PutJsonAsync` &ndash; Sends an HTTP PUT request, including JSON-encoded content.
117+
* `PutAsJsonAsync` &ndash; Sends an HTTP PUT request, including JSON-encoded content.
106118

107119
In the following code, `_editItem` values for `Name` and `IsCompleted` are provided by bound elements of the component. The item's `Id` is set when the item is selected in another part of the UI and `EditItem` is called. The `SaveItem` method is triggered by selecting the Save `<button>` element. See the sample app for a complete example.
108120

@@ -125,9 +137,11 @@ JSON helper methods send requests to a URI (a web API in the following examples)
125137
}
126138
127139
private async Task SaveItem() =>
128-
await Http.PutJsonAsync($"api/TodoItems/{_editItem.Id}, _editItem);
140+
await Http.PutAsJsonAsync($"api/TodoItems/{_editItem.Id}, _editItem);
129141
}
130142
```
143+
144+
Calls to `PutAsJsonAsync` return an <xref:System.Net.Http.HttpResponseMessage>.
131145

132146
<xref:System.Net.Http> includes additional extension methods for sending HTTP requests and receiving HTTP responses. [HttpClient.DeleteAsync](xref:System.Net.Http.HttpClient.DeleteAsync*) is used to send an HTTP DELETE request to a web API.
133147

aspnetcore/blazor/hosting-model-configuration.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,36 @@ Obtain the app's environment in a component by injecting `IWebAssemblyHostEnviro
6060
<p>Environment: @HostEnvironment.Environment</p>
6161
```
6262

63+
During startup, the `WebAssemblyHostBuilder` exposes the `IWebAssemblyHostEnvironment` through the `HostEnvironment` property, which enables developers to have environment-specific logic in their code:
64+
65+
```csharp
66+
if (builder.HostEnvironment.Environment == "Custom")
67+
{
68+
...
69+
};
70+
```
71+
72+
The following convenience extension methods permit checking the current environment for Development, Production, Staging, and custom environment names:
73+
74+
* `IsDevelopment()`
75+
* `IsProduction()`
76+
* `IsStaging()`
77+
* `IsEnvironment("{ENVIRONMENT NAME}")
78+
79+
```csharp
80+
if (builder.HostEnvironment.IsStaging())
81+
{
82+
...
83+
};
84+
85+
if (builder.HostEnvironment.IsEnvironment("Custom"))
86+
{
87+
...
88+
};
89+
```
90+
91+
The `IWebAssemblyHostEnvironment.BaseAddress` property can be used during startup when the `NavigationManager` service isn't available.
92+
6393
### Configuration
6494

6595
As of the ASP.NET Core 3.2 Preview 3 release ([current release is 3.2 Preview 4](xref:blazor/get-started)), Blazor WebAssembly supports configuration from:

aspnetcore/fundamentals/environments/3.1sample/EnvironmentsSample/StartupMethodConventions.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,7 @@ public void ConfigureStaging(IApplicationBuilder app, IWebHostEnvironment env)
9090

9191
public static class MyTrace
9292
{
93-
public static void TraceMessage([CallerMemberName]
94-
string memberName = "")
93+
public static void TraceMessage([CallerMemberName] string memberName = "")
9594
{
9695
Console.WriteLine($"Method: {memberName}");
9796
}

aspnetcore/toc.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@
357357
uid: blazor/handle-errors
358358
- name: Debug WebAssembly
359359
uid: blazor/debug
360-
- name: Call a web API
360+
- name: Call a web API from WebAssembly
361361
uid: blazor/call-web-api
362362
- name: Progressive Web Applications
363363
uid: blazor/progressive-web-app

0 commit comments

Comments
 (0)