hanushi
hanushi

Reputation: 1269

Deploy .NET Blazor web assembly application in Azure Static WebApp - API error 404

I'm trying to deploy a .NET Blazor web assembly application in Azure Static WebApp. I followed the instructions in this document.

https://learn.microsoft.com/en-us/azure/static-web-apps/deploy-blazor.

The web app is deployed and I could see the website, but the API throws a 404 - not found error.

DeployedApp-screenshot

get-api-throw-404

This is my gitlab-ci.yaml file

stages:
  - deploy

variables:
  API_TOKEN: $AZURE_STATIC_WEB_APPS_API_TOKEN
  APP_PATH: '$CI_PROJECT_DIR/ExpenseTracker.Client'
  OUTPUT_PATH: 'wwwroot'
  API_PATH: '$CI_PROJECT_DIR/ExpenseTracker.Server'
  PUBLISH_DIR: '$CI_PROJECT_DIR/publish'

deploy:
  stage: deploy
  image: registry.gitlab.com/static-web-apps/azure-static-web-apps-deploy
  script:
    - echo "App deployed successfully."

Gitlab-job-done-ss

This is my staticwebapp.config.json file

{
    "routes": [
        {
            "route": "/api/*",
            "serve": "/api"
        }
    ],
    "navigationFallback": {
        "rewrite": "/index.html"
    }
}

ExpenseTracker.Server program.cs:

using System.Text.Json.Serialization;
using DinkToPdf;
using DinkToPdf.Contracts;
using ExpenseTracker.Server.AppDbContext;
using ExpenseTracker.Server.Entities;
using ExpenseTracker.Server.Services;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

builder.Services.AddControllers().AddJsonOptions(x =>
                x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

builder.Services.AddRazorPages();  // Combine razor pages and api

// For Entity Framework
builder.Services.AddDbContext<ExpenseTrackerDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

// For DI registration
builder.Services.AddTransient<IExpenseTrackerService, ExpenseTrackerService>();

builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}

app.UseHttpsRedirection();

app.UseStaticFiles(); // to laod wasm static files

app.UseBlazorFrameworkFiles(); //  a special middleware component to serve the client 

app.UseAuthorization();

app.MapRazorPages(); // Combine razor pages and api

app.MapControllers();// handle /api

app.MapFallbackToFile("index.html");  // handle  everything else

app.Run();

ExpenseTracker.Client program.cs:

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using ExpenseTracker.Client;
using MudBlazor.Services;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddMudServices();

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

await builder.Build().RunAsync();

Why does the API return a 404 error while the web app URL is functioning fine?

Upvotes: 0

Views: 121

Answers (1)

Aslesha Kantamsetti
Aslesha Kantamsetti

Reputation: 1408

As I mentioned in Comments, as per this document if you use your own Api it would be hosted in Azure Function, Azure Web App, Api Management or Containers apps.

I edited your code to deploy Api to azure app service.

I added below lines to the program.cs file and comment the lines which is linked to the blazor web app.

builder.Services.AddSwaggerGen();
app.UseSwagger();
app.UseSwaggerUI(x =>
{
    x.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
    if (app.Environment.IsDevelopment())
        x.RoutePrefix = "swagger"; 
    else
        x.RoutePrefix = string.Empty;
    }
);

Below is the complete Program.cs file:

using System.Text.Json.Serialization;
using DinkToPdf;
using DinkToPdf.Contracts;
using ExpenseTracker.Server.AppDbContext;
using ExpenseTracker.Server.Entities;
using ExpenseTracker.Server.Services;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
builder.Services.AddControllers().AddJsonOptions(x =>                x.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowBlazorClient",
        builder =>
        {
            builder.WithOrigins("*")
                   .AllowAnyHeader()
                   .AllowAnyMethod();
        });
});
builder.Services.AddDbContext<ExpenseTrackerDbContext>(options =>
{    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddTransient<IExpenseTrackerService, ExpenseTrackerService>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(x =>
{
    x.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");
    if (app.Environment.IsDevelopment())
        x.RoutePrefix = "swagger"; 
    else
        x.RoutePrefix = string.Empty;  
}
);
app.UseHttpsRedirection();
app.UseCors("AllowBlazorClient");
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("index.html"); 
app.Run();

After Successfully deployed to the azure web app I got below output:

Azure App Service:

enter image description here

enter image description here

I added below azure web app uri to the Blazor client app Program.cs file.

https://<AzureWebAppName>.azurewebsites.net

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using ExpenseTracker.Client;
using MudBlazor.Services;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddMudServices();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri("https://kaexpensetrackerserver.azurewebsites.net") });
await builder.Build().RunAsync();

I enable the Cors in the Api by placing static web api uri in the Allowed Origins as shown below.

enter image description here

Below is the Azure Static web app output:

enter image description here

Upvotes: 0

Related Questions