Blazor WebAssembly for Headless CMS on Azure Static Web Apps

One of the crucial fashionable eventualities to construct a static web site is to run a weblog web site for myself or my organisation. WordPress is the most well-liked service for this goal. Now, you need to migrate your WordPress weblog web site to a static web site, however it does not look simple.

What should you nonetheless need to use the WordPress web site to jot down content material however solely need to refresh the UI outdoors the positioning? What should you may even use C# for it via Blazor WebAssembly? You at the moment are in a position to make use of the prevailing WordPress web site as the info supply of reality and construct a UI in a separate occasion together with your most well-liked technique. Does that sound enticing?

All through this submit, I’ll talk about methods to use the serviced WordPress occasion because the headless CMS, construct the Blazor WebAssembly app to utilize the WordPress as a knowledge supply, and host it to Azure Static Web Apps.

You may obtain the pattern app code from this GitHub repository:

Blazor WASM with Azure Capabilities on ASWA for headless CMS

This offers a pattern headless CMS app utilizing Blazor WebAssembly hosted on Azure Static Net Apps.


Serviced WordPress Web site Occasion

I’ve bought a serviced WordPress web site that’s not maintained however archived.

To be able to use this web site as a knowledge supply, I want to have the ability to entry to the contents via APIs. Happily, WordPress offers filled with HTTP API endpoints. Enter the next command in your terminal.

curl -X GET<site-name>
Enter fullscreen mode

Exit fullscreen mode

Alternatively, you should use your most well-liked UI software like Postman to get the checklist of contents:

Result from WordPress API

You get the contents. All you must do now could be to render the contents on the Blazore WASM app. There are two approaches to it:

  1. Immediately name the API from the Blazor WASM app, or
  2. Name the API from the Blazor WASM app via the proxy API app

Each approaches have execs and cons, however let’s make it with the second method.

Proxy API Utility

We do not want the proxy API app for Azure Static Web Apps. Nevertheless, if you must overcome the CORS challenge, deal with numerous APIs, or cope with some safety considerations, utilizing the proxy API is an effective possibility. As a result of Azure Static Net Apps natively helps this proxy API function, we are able to merely use it. To begin with create an HTTP trigger of Azure Functions app.

Outline GetPosts for the WordPress API endpoint and create an HttpClient occasion.

public static class PostHttpTrigger
    personal const string GetPosts = "{0}/posts";
    personal static HttpClient http = new HttpClient();
Enter fullscreen mode

Exit fullscreen mode

If you happen to add the OpenAPI extension to your perform app, your Blazor WASM app can simply entry this proxy API. I am going to deal with this half later on this submit.

    [OpenApiOperation(operationId: "posts.get", tags: new[] { "posts" })]
    [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(PostCollection), Description = "The OK response")]
    public static async Process<IActionResult> GetPostsAsync(
        [HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "posts")] HttpRequest req,
        ILogger log)
Enter fullscreen mode

Exit fullscreen mode

Get the precise WordPress web site title from the atmosphere variables.

        var requestUri = new Uri(string.Format(GetPosts, Surroundings.GetEnvironmentVariable("SITE__NAME")));
Enter fullscreen mode

Exit fullscreen mode

Lastly, name the WordPress API and deserialise the outcome to the PostCollection object.

        var json = await http.GetStringAsync(requestUri).ConfigureAwait(false);
        var posts = JsonConvert.DeserializeObject<PostCollection>(json);

        return new OkObjectResult(posts);
Enter fullscreen mode

Exit fullscreen mode

Listed here are the definitions of the PostCollection class and its subclasses. Though the WordPress API returns an enormous number of outcomes, we solely want a few of them outlined within the PostCollection class.

public class PostCollection
    public digital int Discovered { get; set; }

    public digital Checklist<PostItem> Posts { get; set; }

    public digital Metadata Metadata { get; set; }

public class PostItem
    public digital int PostId { get; set; }

    public digital Creator Creator { get; set; }

    public digital DateTimeOffset DatePublished { get; set; }

    public digital string Title { get; set; }

    public digital string Url { get; set; }

    public digital string Excerpt { get; set; }

    public digital string Content material { get; set; }

public class Creator
    public digital int AuthorId { get; set; }

    public digital string FirstName { get; set; }

    public digital string Surname { get; set; }

    public digital string Identify { get; set; }

public class Metadata
    public digital Dictionary<string, string> Hyperlinks { get; set; }

    public digital string NextPage { get; set; }

    public digital bool IsWordpressCom { get; set; }
Enter fullscreen mode

Exit fullscreen mode

Lastly, configure the native.settings.json file. We set it to this file as we beforehand referred to the atmosphere variable of SITE__NAME. Along with that, we set the CORS for the Blazor WebAssembly app integration.

  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",

    "SITE__NAME": "<site-name>"
  "Host": {
    "CORS": "*"
Enter fullscreen mode

Exit fullscreen mode

All set! Run the proxy API app, and you will notice the outcome like beneath:

Result from Proxy API

The OpenAPI doc URL to this proxy API app is among the following:

  • http://localhost:7071/api/swagger.json – OpenAPI V2
  • http://localhost:7071/api/openapi/v2.json – OpenAPI V2
  • http://localhost:7071/api/openapi/v3.json – OpenAPI V3

Blazor WebAssembly Utility

Open Visual Studio and create a brand new Blazor WebAssembly mission.

Blazor WASM Project

Give it the title of WebApp, and go away the remaining as default. As soon as the app is created, run the app by typing the F5 key, and you will notice the display like this:

Blazor WASM App

It is time to connect with the proxy API to this Blazor app. First, make it possible for the proxy API app is working background. Then, click on the “Linked Companies” menu.

Connected Service Menu

Then click on the “➕” button.

Add Reference

Select the “OpenAPI” possibility as a service reference.

Choose OpenAPI

Enter the OpenAPI URL, give the namespace of WebApp.Proxies and sophistication title of ProxyClient, and click on the “End” button.

Enter OpenAPI Details

You may see the proxy API is added to the Blazor app.

OpenAPI Reference Added

Click on the three dots on the right-hand aspect and choose the “View generated code” menu. Are you able to see the auto-generated code from the OpenAPI doc?

Auto-generated Code from OpenAPI

We simply have to eat this code. First, open the Program.cs file and add the dependency of the ProxyClient occasion.

Whereas creating this app in your native machine, the default base URL is http://localhost:7071/api. However as soon as it is deployed to Azure, it should comply with the precise host tackle (line #8-12).

builder.Companies.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

// Add these traces to inject the dependency of ProxyClient
builder.Companies.AddScoped(sp =>
    var shopper = sp.GetService<HttpClient>();
    var api = new ProxyClient(shopper);
    if (!builder.HostEnvironment.IsDevelopment())
        var baseUrl = $"{builder.HostEnvironment.BaseAddress.TrimEnd("")}/api";
        api.BaseUrl = baseUrl;

    return api;
Enter fullscreen mode

Exit fullscreen mode

By this far, your Blazor app is now freely accessible to the proxy API. So, let’s implement this half. First, we merely modify the index.razor web page and render the checklist of weblog posts on this submit.

Inject the dependency of ProxyClient added via Program.cs.

@web page ""

@* Inject ProxyClient dependency *@
@utilizing WebApp.Proxies
@inject ProxyClient Api
Enter fullscreen mode

Exit fullscreen mode

Add the HTML bits and items slightly below the <SurveyPrompt> element that handles the checklist of weblog posts.

<SurveyPrompt Title="How is Blazor working for you?" />

@if (posts == null)
    <desk class="desk">
            @foreach (var submit in posts)
                    <td><a href="@submit.URL">@submit.Title</a></td>
Enter fullscreen mode

Exit fullscreen mode

Here is the precise code to name the proxy API. By this proxy API, this web page receives the checklist of weblog posts.

@code {
    personal Checklist<PostItem> posts;

    protected override async Process OnInitializedAsync()
        var assortment = await Api.Posts_getAsync().ConfigureAwait(false);
        posts = assortment?.Posts.ToList();
Enter fullscreen mode

Exit fullscreen mode

It is completed! Run the Blazor app once more. You may see the checklist of weblog posts populated from WordPress.

List of Blog Posts

You must push all of the code to the GitHub repository.

Azure Static Net Apps Internet hosting

All coding elements have been accomplished! Now it is time to publish the app to Azure Static Web Apps. I am not going to stroll via this half. As an alternative, listed below are hyperlinks to my earlier posts in regards to the deployment.

When you full publishing your Blazor WebAssembly app with the proxy API app, go to the web site to substantiate whether or not every part is OK or not.

List of Blog Posts on Azure

To date, I’ve walked via methods to construct a Blazor WebAssembly app with an Azure Functions proxy API and use serviced WordPress web site as a knowledge supply. Additionally, I’ve revealed this app to Azure Static Web Apps occasion. Though this submit has solely applied the high-level ideas, it has mainly touched virtually every part you want. Subsequently, it is as much as you to make use of as many API endpoints as attainable and make the UI prettier. Then, you may nonetheless use the prevailing WordPress web site as your knowledge supply of reality.

Add a Comment

Your email address will not be published. Required fields are marked *