Skip to content

Commit 56ad011

Browse files
authored
Call web API article updates 8.0 (#30180)
1 parent c261c3a commit 56ad011

File tree

4 files changed

+60
-33
lines changed

4 files changed

+60
-33
lines changed

aspnetcore/blazor/call-web-api.md

Lines changed: 48 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,30 @@ ms.author: riande
77
ms.custom: mvc
88
ms.date: 04/06/2023
99
uid: blazor/call-web-api
10-
zone_pivot_groups: blazor-hosting-models
10+
zone_pivot_groups: blazor-render-modes
1111
---
1212
# Call a web API from ASP.NET Core Blazor
1313

1414
[!INCLUDE[](~/includes/not-latest-version.md)]
1515

1616
This article describes how to call a web API from a Blazor app.
1717

18+
[!INCLUDE[](~/blazor/includes/location-client-and-server-net31-or-later.md)]
19+
1820
> [!NOTE]
1921
> The code examples in this article adopt [nullable reference types (NRTs) and .NET compiler null-state static analysis](xref:migration/50-to-60#nullable-reference-types-nrts-and-net-compiler-null-state-static-analysis), which are supported in ASP.NET Core 6.0 or later. When targeting ASP.NET Core 5.0 or earlier, remove the null type designation (`?`) from the `string?`, `TodoItem[]?`, `WeatherForecast[]?`, and `IEnumerable<GitHubBranch>?` types in the article's examples.
2022
2123
:::zone pivot="webassembly"
2224

2325
> [!NOTE]
24-
> This article has loaded **Blazor WebAssembly** coverage for calling web APIs. The [Blazor Server coverage](?pivots=server) addresses the following subjects:
26+
> This article has loaded **WebAssembly** render mode coverage for calling web APIs. The [Server render mode coverage](?pivots=server) addresses the following subjects:
2527
>
2628
> * Use of the `HttpClient` factory infrastructure to provide an `HttpClient` to the app.
27-
> * Cross-Origin Resource Sharing (CORS) pertaining to Blazor Server apps.
29+
> * Cross-Origin Resource Sharing (CORS) pertaining to server-side components.
2830
> * Blazor framework component examples for testing web API access.
2931
> * Additional resources for developing Blazor Server apps that call a web API.
3032
31-
[Blazor WebAssembly](xref:blazor/hosting-models#blazor-webassembly) apps call web APIs using a preconfigured <xref:System.Net.Http.HttpClient> service, which is focused on making requests back to the server of origin. Additional <xref:System.Net.Http.HttpClient> service configurations for other web APIs can be created in developer code. Requests are composed using Blazor JSON helpers or with <xref:System.Net.Http.HttpRequestMessage>. Requests can include [Fetch API](https://developer.mozilla.org/docs/Web/API/Fetch_API) option configuration.
33+
Client-side components call web APIs using a preconfigured <xref:System.Net.Http.HttpClient> service, which is focused on making requests back to the server of origin. Additional <xref:System.Net.Http.HttpClient> service configurations for other web APIs can be created in developer code. Requests are composed using Blazor JSON helpers or with <xref:System.Net.Http.HttpRequestMessage>. Requests can include [Fetch API](https://developer.mozilla.org/docs/Web/API/Fetch_API) option configuration.
3234

3335
## Examples in this article
3436

@@ -51,7 +53,25 @@ public class TodoItem
5153

5254
For guidance on how to create a server-side web API, see <xref:tutorials/first-web-api>. For information on Cross-Origin Resource Sharing (CORS), see the *Cross-Origin Resource Sharing (CORS)* section later in this article.
5355

54-
The Blazor WebAssembly examples that demonstrate obtaining weather data from a server API are based on a hosted Blazor WebAssembly solution created from the [Blazor WebAssembly project template](xref:blazor/project-structure#blazor-webassembly).
56+
The Blazor examples that demonstrate obtaining weather data from a server API are based on a hosted Blazor WebAssembly solution created from the [Blazor WebAssembly project template](xref:blazor/project-structure#blazor-webassembly).
57+
58+
:::moniker range=">= aspnetcore-8.0"
59+
60+
<!-- UPDATE 8.0 Cross-link SSR and CSR -->
61+
62+
For server-side components in Blazor Web Apps that require server interactivity, add the server-side rendering (SSR) attribute to the top of the component:
63+
64+
```razor
65+
@attribute [RenderModeServer]
66+
```
67+
68+
For client-side components in Blazor Web Apps that require client interactivity, add the client-side rendering (CSR) attribute to the top of the component:
69+
70+
```razor
71+
@attribute [RenderModeWebAssembly]
72+
```
73+
74+
:::moniker-end
5575

5676
## Package
5777

@@ -61,7 +81,7 @@ The [`System.Net.Http.Json`](https://www.nuget.org/packages/System.Net.Http.Json
6181

6282
## Add the `HttpClient` service
6383

64-
In `Program.cs`, add an <xref:System.Net.Http.HttpClient> service if it isn't already present from a Blazor project template used to create the app:
84+
In the `Program` file, add an <xref:System.Net.Http.HttpClient> service if it isn't already present from a Blazor project template used to create the app:
6585

6686
```csharp
6787
builder.Services.AddScoped(sp =>
@@ -359,7 +379,7 @@ public static class JSONPatchInputFormatter
359379

360380
Configure the web API's controllers to use the `Microsoft.AspNetCore.Mvc.NewtonsoftJson` package and process PATCH requests with the JSON PATCH input formatter. Insert the `JSONPatchInputFormatter` in the first position of MVC's input formatter collection so that it processes requests prior to any other input formatter.
361381

362-
In `Program.cs` modify the call to <xref:Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllers%2A>:
382+
In the `Program` file modify the call to <xref:Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllers%2A>:
363383

364384
```csharp
365385
builder.Services.AddControllers(options =>
@@ -449,7 +469,7 @@ Add the [`Microsoft.Extensions.Http`](https://www.nuget.org/packages/Microsoft.E
449469

450470
[!INCLUDE[](~/includes/package-reference.md)]
451471

452-
In `Program.cs`:
472+
In the `Program` file:
453473

454474
```csharp
455475
builder.Services.AddHttpClient("WebAPI", client =>
@@ -464,7 +484,7 @@ In the following component code:
464484
> [!NOTE]
465485
> When targeting ASP.NET Core 5.0 or earlier, add `@using` directives to the following component for <xref:System.Net.Http?displayProperty=fullName>, <xref:System.Net.Http.Json?displayProperty=fullName>, and <xref:System.Threading.Tasks?displayProperty=fullName>.
466486
467-
`Pages/FetchDataViaFactory.razor`:
487+
`FetchDataViaFactory.razor`:
468488

469489
```razor
470490
@page "/fetch-data-via-factory"
@@ -543,7 +563,7 @@ public class WeatherForecastHttpClient
543563
}
544564
```
545565

546-
In `Program.cs`:
566+
In the `Program` file:
547567

548568
```csharp
549569
builder.Services.AddHttpClient<WeatherForecastHttpClient>(client =>
@@ -560,7 +580,7 @@ In the following component code:
560580
> [!NOTE]
561581
> When targeting ASP.NET Core 5.0 or earlier, add an `@using` directive to the following component for <xref:System.Threading.Tasks?displayProperty=fullName>.
562582
563-
`Pages/FetchDataViaTypedHttpClient.razor`:
583+
`FetchDataViaTypedHttpClient.razor`:
564584

565585
```razor
566586
@page "/fetch-data-via-typed-httpclient"
@@ -606,11 +626,11 @@ else
606626
> [!NOTE]
607627
> When targeting ASP.NET Core 5.0 or earlier, add `@using` directives to the following component for <xref:System.Net.Http?displayProperty=fullName> and <xref:System.Net.Http.Json?displayProperty=fullName>.
608628
609-
`Pages/TodoRequest.razor`:
629+
`TodoRequest.razor`:
610630

611631
:::code language="razor" source="~/../blazor-samples/7.0/BlazorSample_WebAssembly/Pages/call-web-api/TodoRequest.razor":::
612632

613-
Blazor WebAssembly's implementation of <xref:System.Net.Http.HttpClient> uses [Fetch API](https://developer.mozilla.org/docs/Web/API/fetch). Fetch API allows the configuration of several [request-specific options](https://developer.mozilla.org/docs/Web/API/fetch#Parameters). Options can be configured with <xref:System.Net.Http.HttpRequestMessage> extension methods shown in the following table.
633+
Blazor's client-side implementation of <xref:System.Net.Http.HttpClient> uses [Fetch API](https://developer.mozilla.org/docs/Web/API/fetch). Fetch API allows the configuration of several [request-specific options](https://developer.mozilla.org/docs/Web/API/fetch#Parameters). Options can be configured with <xref:System.Net.Http.HttpRequestMessage> extension methods shown in the following table.
614634

615635
| Extension method | Fetch API request property |
616636
| --- | --- |
@@ -635,7 +655,7 @@ For more information on Fetch API options, see [MDN web docs: WindowOrWorkerGlob
635655

636656
The following example calls a web API. The example requires a running web API based on the sample app described by the <xref:tutorials/first-web-api> article. This example makes requests to the web API at `https://localhost:10000/api/TodoItems`. If a different web API address is used, update the `ServiceEndpoint` constant value in the component's `@code` block.
637657

638-
The following example makes a [Cross-Origin Resource Sharing (CORS)](xref:security/cors) request from `http://localhost:5000` or `https://localhost:5001` to the web API. Add the following CORS Middleware configuration to the web API's service's `Program.cs` file:
658+
The following example makes a [Cross-Origin Resource Sharing (CORS)](xref:security/cors) request from `http://localhost:5000` or `https://localhost:5001` to the web API. Add the following CORS Middleware configuration to the web API's service's `Program` file:
639659

640660
```csharp
641661
app.UseCors(policy =>
@@ -648,7 +668,7 @@ Adjust the domains and ports of `WithOrigins` as needed for the Blazor app. For
648668

649669
By default, ASP.NET Core apps use ports 5000 (HTTP) and 5001 (HTTPS). To run both apps on the same machine at the same time for testing, use a different port for the web API app (for example, port 10000). For more information on setting the port, see <xref:fundamentals/servers/kestrel/endpoints>.
650670

651-
`Pages/CallWebAPI.razor`:
671+
`CallWebAPI.razor`:
652672

653673
:::code language="razor" source="~/../blazor-samples/7.0/BlazorSample_WebAssembly/Pages/call-web-api/CallWebAPI.razor":::
654674

@@ -665,7 +685,7 @@ In <xref:Microsoft.AspNetCore.Components.ComponentBase.OnInitializedAsync%2A> on
665685
> [!NOTE]
666686
> When targeting ASP.NET Core 5.0 or earlier, add `@using` directives to the following component for <xref:System.Net.Http?displayProperty=fullName>, <xref:System.Net.Http.Json?displayProperty=fullName>, and <xref:System.Threading.Tasks?displayProperty=fullName>.
667687
668-
`Pages/ReturnHTMLOnException.razor`:
688+
`ReturnHTMLOnException.razor`:
669689

670690
```razor
671691
@page "/return-html-on-exception"
@@ -728,33 +748,33 @@ For more information, see <xref:blazor/fundamentals/handle-errors>.
728748
:::zone pivot="server"
729749

730750
> [!NOTE]
731-
> This article has loaded **Blazor Server** coverage for calling web APIs. The [Blazor WebAssembly coverage](?pivots=webassembly) addresses the following subjects:
751+
> This article has loaded **Server** render mode coverage for calling web APIs. The [WebAssembly render mode coverage](?pivots=webassembly) addresses the following subjects:
732752
>
733-
> * Blazor WebAssembly examples based on an client-side WebAssembly app that calls a web API to create, read, update, and delete todo list items.
753+
> * Client-side examples that call a web API to create, read, update, and delete todo list items.
734754
> * `System.Net.Http.Json` package.
735755
> * `HttpClient` service configuration.
736756
> * `HttpClient` and JSON helpers (`GetFromJsonAsync`, `PostAsJsonAsync`, `PutAsJsonAsync`, `DeleteAsync`).
737757
> * `IHttpClientFactory` services and the configuration of a named `HttpClient`.
738758
> * Typed `HttpClient`.
739759
> * `HttpClient` and `HttpRequestMessage` to customize requests.
740-
> * Call web API example with Cross-Origin Resource Sharing (CORS) and how CORS pertains to Blazor WebAssembly apps.
760+
> * Call web API example with Cross-Origin Resource Sharing (CORS) and how CORS pertains to client-side components.
741761
> * How to handle web API response errors in developer code.
742762
> * Blazor framework component examples for testing web API access.
743-
> * Additional resources for developing Blazor WebAssembly apps that call a web API.
763+
> * Additional resources for developing client-side components that call a web API.
744764
745-
[Blazor Server](xref:blazor/hosting-models#blazor-server) apps call web APIs using <xref:System.Net.Http.HttpClient> instances, typically created using <xref:System.Net.Http.IHttpClientFactory>. For guidance that applies to Blazor Server, see <xref:fundamentals/http-requests>.
765+
Server-based components call web APIs using <xref:System.Net.Http.HttpClient> instances, typically created using <xref:System.Net.Http.IHttpClientFactory>. For guidance that applies to server-side apps, see <xref:fundamentals/http-requests>.
746766

747-
A Blazor Server app doesn't include an <xref:System.Net.Http.HttpClient> service by default. Provide an <xref:System.Net.Http.HttpClient> to the app using the [`HttpClient` factory infrastructure](xref:fundamentals/http-requests).
767+
A server-side app doesn't include an <xref:System.Net.Http.HttpClient> service by default. Provide an <xref:System.Net.Http.HttpClient> to the app using the [`HttpClient` factory infrastructure](xref:fundamentals/http-requests).
748768

749-
In `Program.cs`:
769+
In the `Program` file:
750770

751771
```csharp
752772
builder.Services.AddHttpClient();
753773
```
754774

755-
The following Blazor Server Razor component makes a request to a web API for GitHub branches similar to the *Basic Usage* example in the <xref:fundamentals/http-requests> article.
775+
The following Razor component makes a request to a web API for GitHub branches similar to the *Basic Usage* example in the <xref:fundamentals/http-requests> article.
756776

757-
`Pages/CallWebAPI.razor`:
777+
`CallWebAPI.razor`:
758778

759779
```razor
760780
@page "/call-web-api"
@@ -828,9 +848,9 @@ Browser security restricts a webpage from making requests to a different domain
828848

829849
:::zone pivot="webassembly"
830850

831-
For information on CORS requests in Blazor WebAssembly apps, see <xref:blazor/security/webassembly/additional-scenarios#cross-origin-resource-sharing-cors>.
851+
For information on client-side CORS requests, see <xref:blazor/security/webassembly/additional-scenarios#cross-origin-resource-sharing-cors>.
832852

833-
For information on CORS, see <xref:security/cors>. The article's examples don't pertain directly to Blazor WebAssembly apps, but the article is useful for learning general CORS concepts.
853+
For information on CORS, see <xref:security/cors>. The article's examples don't pertain directly to Razor component scenarios, but the article is useful for learning general CORS concepts.
834854

835855
:::zone-end
836856

@@ -878,7 +898,7 @@ Various network tools are publicly available for testing web API backend apps di
878898
:::zone pivot="webassembly"
879899

880900
* <xref:blazor/security/webassembly/additional-scenarios>: Includes coverage on using <xref:System.Net.Http.HttpClient> to make secure web API requests.
881-
* <xref:security/cors>: Although the content applies to ASP.NET Core apps, not Blazor WebAssembly apps, the article covers general CORS concepts.
901+
* <xref:security/cors>: Although the content applies to ASP.NET Core apps, not Razor components, the article covers general CORS concepts.
882902
* [Cross-Origin Resource Sharing (CORS) at W3C](https://www.w3.org/TR/cors/)
883903
* [Fetch API](https://developer.mozilla.org/docs/Web/API/fetch)
884904

aspnetcore/blazor/file-uploads.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -809,7 +809,6 @@ A security best practice for production apps is to avoid sending error messages
809809
>
810810
> For more information on security considerations when uploading files to a server, see <xref:mvc/models/file-uploads#security-considerations>.
811811
812-
813812
:::moniker range=">= aspnetcore-8.0"
814813
815814
> [!NOTE]

aspnetcore/blazor/forms-and-input-components.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2010,15 +2010,15 @@ If the server API returns the preceding default JSON response, it's possible for
20102010
}
20112011
```
20122012

2013-
To modify the server API's response to make it only return the validation errors, change the delegate that's invoked on actions that are annotated with <xref:Microsoft.AspNetCore.Mvc.ApiControllerAttribute> in `Program.cs`. For the API endpoint (`/StarshipValidation`), return a <xref:Microsoft.AspNetCore.Mvc.BadRequestObjectResult> with the <xref:Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary>. For any other API endpoints, preserve the default behavior by returning the object result with a new <xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails>.
2013+
To modify the server API's response to make it only return the validation errors, change the delegate that's invoked on actions that are annotated with <xref:Microsoft.AspNetCore.Mvc.ApiControllerAttribute> in the `Program` file. For the API endpoint (`/StarshipValidation`), return a <xref:Microsoft.AspNetCore.Mvc.BadRequestObjectResult> with the <xref:Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary>. For any other API endpoints, preserve the default behavior by returning the object result with a new <xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails>.
20142014

2015-
Add the <xref:Microsoft.AspNetCore.Mvc?displayProperty=fullName> namespace to the top of the `Program.cs` file in the **:::no-loc text="Server":::** app:
2015+
Add the <xref:Microsoft.AspNetCore.Mvc?displayProperty=fullName> namespace to the top of the `Program` file in the **:::no-loc text="Server":::** app:
20162016

20172017
```csharp
20182018
using Microsoft.AspNetCore.Mvc;
20192019
```
20202020

2021-
In `Program.cs`, locate the <xref:Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllersWithViews%2A> extension method and add the following call to <xref:Microsoft.Extensions.DependencyInjection.MvcCoreMvcBuilderExtensions.ConfigureApiBehaviorOptions%2A>:
2021+
In the `Program` file, locate the <xref:Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddControllersWithViews%2A> extension method and add the following call to <xref:Microsoft.Extensions.DependencyInjection.MvcCoreMvcBuilderExtensions.ConfigureApiBehaviorOptions%2A>:
20222022

20232023
```csharp
20242024
builder.Services.AddControllersWithViews()
@@ -2777,7 +2777,7 @@ public class SaladChef
27772777
}
27782778
```
27792779

2780-
Register `SaladChef` in the app's DI container in `Program.cs`:
2780+
Register `SaladChef` in the app's DI container in the `Program` file:
27812781

27822782
```csharp
27832783
builder.Services.AddTransient<SaladChef>();

aspnetcore/zone-pivot-groups.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,11 @@ groups:
6666
title: Port/domain hosting
6767
- id: route-subpath
6868
title: Route subpath hosting
69+
- id: blazor-render-modes
70+
title: Blazor Render Mode
71+
prompt: Choose a Blazor render mode
72+
pivots:
73+
- id: server
74+
title: Server
75+
- id: webassembly
76+
title: WebAssembly

0 commit comments

Comments
 (0)