2

I’m brand new to Blazor and I’m trying to learn by converting an old website/web API project into a .Net 6 Blazor Server app where I plan to have both the UI and the API in the same application. I created a Controllers folder and added a controller called ApiController. I also set up Entity Framework and created my Entity classes for my SQL database tables. I’ve added the first HTTPGET route and tried hitting it through Postman to see if it will work. However, I keep getting a message that the page can not be found.

I thinking I need to add something to the Program.cs to let it know that I’m wanting to use APIs and Routing but, in my research, I’m not finding what I’m missing or what needs to be added. Most examples want to use a WASM project which probably has the API and Routing information built in.

This is the URL I'm trying to hit.

https://localhost:7168/api/usersadmin/GetAppNames

ApiController.cs

using Microsoft.AspNetCore.Mvc;
using UsersAdmin_AS.Data;

namespace UsersAdmin_AS.Controllers
{
    [Route("api/UsersAdmin/[action]")]
    [ApiController]
    public class ApiController : ControllerBase
    {    
        [HttpGet]
        [Route("GetAppNames")]
        public List<string> GetAppNames()
        {
            //logger.Info("GetAppNames");
            List<string> listAppNames = new List<string>();

            try
            {
                var dataManager = new DataManager();

                listAppNames = dataManager.GetAppNames();
            }
            catch (Exception ex)
            {
                //logger.Error("ERROR: {0} | {1} | {2}", ex.Message, ex.StackTrace, ex.InnerException);
                throw;
            }

            return listAppNames;
        }
}

Program.cs

using UsersAdmin_AS.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();
Caverman
  • 3,371
  • 9
  • 59
  • 115
  • I don't have a good way to test this right now, but you don't need "[action'" in your class route and a route on each action. You are likely doubling your action name. https://stackoverflow.com/questions/18661946/web-api-route-to-action-name Try accessing 'https://localhost:7168/api/usersadmin/GetAppNames/GetAppNames' to see if that's what's happening. – computercarguy Dec 22 '22 at 16:18
  • Thanks for the tip but that didn't make a difference either. I even tried removing the action name and just using [Route("api/UsersAdmin")] but still get the same error about not finding the page. The message is actually "Sorry, there's nothing at this address". I still think I'm missing something in the Program.cs page to let it know to use API and/or Routing. – Caverman Dec 22 '22 at 16:26

2 Answers2

2

I found this post and it fixed my issue.

https://stackoverflow.com/questions/70583469/host-web-api-in-blazor-server-application

This is the route I used at the top of the controller.

[Route("api/UsersAdmin/")]

I used this as my specific route.

[HttpGet]
[Route("GetAppNames")]

I added the builder.Services.AddControllers(), commented out the app.MapBlazorHub() and app.MapFallbackToPage("/_Host"). I then added the app.UseEndpoints() function.

Here is my updated Program.cs file.

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using UsersAdmin_AS.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddControllers();

builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

//app.MapBlazorHub();
//app.MapFallbackToPage("/_Host");

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
    endpoints.MapRazorPages();
    endpoints.MapFallbackToPage("/_Host");
});


app.Run();
Caverman
  • 3,371
  • 9
  • 59
  • 115
  • I just change like "app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapBlazorHub(); endpoints.MapRazorPages(); endpoints.MapFallbackToPage("/_Host"); });" ,but I don' t add "builder.Services.AddControllers()" and works fine. – Qing Guo Dec 23 '22 at 02:11
0

Replace [Route("api/UsersAdmin/[action]")] with [Route("api/UsersAdmin/[controller]")]

and comment out [Route("GetAppNames")] in your controller.. Your swagger should show GetAppNames endpoint

Siba Daki
  • 9
  • 2
  • Thanks. I tried that but still get the same message about the page not being available. I don't have swagger turned on. I just created a Blazor Server App through VS2022 and it doesn't seem to have swagger installed. – Caverman Dec 23 '22 at 01:30
  • Does the default server page runs? – Siba Daki Dec 23 '22 at 03:47
  • Thanks for the help. BTW, the default page did work fine. Found the answer and posted it here. I was missing some middleware settings which is what I was kind of assuming. I just didn't know what to put but eventually found it. – Caverman Dec 23 '22 at 20:17