A simple graphical explanation of Blazor's effect on the web development landscape.

HttpClient in Blazor

This post was most recently updated on October 17th, 2019.

Reading Time: 3 minutes.

Blazor is a new (ish) framework for building web UIs with C#. It compiles directly to WebAssembly, cutting out the need to write any pesky JavaScript yourself – pretty neat, if you ask me!

However, developing your web apps with Blazor is a bit different from using ASP.NET MVC, for example. Other people have written great introductions to the tech, so I’ll stick to the problem at hand: Using HttpClient with Blazor.

Description

With Blazor, a lot of your code runs serverside, and you’re using serverside dependencies. One example of this is HTTP queries, to which you need the class HttpClient. However, not all of the “classic” web server stack you might’ve grown to expect is available without configuration – and HttpClient is probably the most obvious dependency that’ll require an additional step to get it up and running.


Solution

Prior to Blazor (and .NET Core) preview 9, the code below was a simple way to get access to the HttpClient via @inject – basically, add the code below into your StartUp.cs’s ConfigureServices method:

if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
{
	// Setup HttpClient for server side in a client side compatible fashion
	services.AddScoped<HttpClient>(s =>
	{
		// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
		var uriHelper = s.GetRequiredService<IUriHelper>();
		return new HttpClient
		{
			BaseAddress = new Uri(uriHelper.GetBaseUri())
		};
	});
}

The way this works in your code elsewhere, no matter which version of ASP.NET Core you’re on, is this:

@inject HttpClient Http
 
...
 
@code {
 
 string yourAPIUrl = "https://yourepicapisite.azurewebsites.net/api/getdata";
 
 protected override async Task OnInitializedAsync()
 {
  // do something with your HttpClient - in this case, GET data from your custom API...
  var t = Http.GetAsync(yourAPIUrl);
 
  ...
 
 }
}

Preview 9 changed the configuration part a bit, though, as UriHelper is not used anymore, but rather replaced with NavigationManager. It’s essentially the same thing in this case – so I just replaced the requested service to be that.

Below, you can see how you can request and use it when configuring the HttpClient:

// Server Side Blazor doesn't register HttpClient by default
if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
{
	// Setup HttpClient for server side in a client side compatible fashion
	services.AddScoped<HttpClient>(s =>
	{
		// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
		var uriHelper = s.GetRequiredService<NavigationManager>();
		return new HttpClient
		{
			BaseAddress = new Uri(uriHelper.BaseUri)
		};
	});
}

Pretty easy and straightforward!

NavMan & UriHelper madness

A quick detour here – UriHelper injection and name has changed back and forth a few times. This post below should explain that a bit more:

References

This tip originally grabbed from here:

https://github.com/aspnet/AspNetCore/issues/7851

Antti K. Koskela

Antti Koskela is a proud digital native nomadic millennial full stack developer (is that enough funny buzzwords? That's definitely enough funny buzzwords!), who works as a Solutions Architect for Valo Intranet, the product that will make you fall in love with your intranet. Working with the global partner network, he's responsible for the success of Valo deployments happening all around the world.

He's been a developer from 2004 (starting with PHP and Java), and he's been bending and twisting SharePoint into different shapes since MOSS. Nowadays he's not only working on SharePoint, but also on .NET projects, Azure, Office 365 and a lot of other stuff.

This is his personal professional (e.g. professional, but definitely personal) blog.
mm

Leave a Reply

avatar
5000
  Subscribe  
Notify of