I'm trying to use a Blazor Server that I would like to do both a UI and host an API. I created a Controllers folder and added a API Controller to it. I've added what I think I need to the Program.cs file to add the ability to use an API Controller. I can start up and build the project but when I use Postman to try to get to the end point, I keep getting an error that says:
"Sorry, there's nothing at this address.".
This is my Postman GET call: https://localhost:7131/api/GetApplicationNames
Program.cs
using Microsoft.EntityFrameworkCore;
using UsersAdmin_BlazorServer.Data;
using UsersAdmin_BlazorServer.Interfaces;
using UsersAdmin_BlazorServer.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllers();
builder.Services.AddServerSideBlazor();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddTransient<IAppManager, AppManager>();
builder.Services.AddTransient<IDataManager, DataManager>();
builder.Services.AddSingleton<WeatherForecastService>();
//Adds DataContext dependency
var connString = builder.Configuration["ConnectionStrings:DbConnection"];
builder.Services.AddDbContext<DataContext>(options =>
{
options.UseSqlServer(connString);
});
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.MapControllers();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
AppController.cs
[ApiController]
[Route("api")]
public class AppController : ControllerBase
{
private readonly ILogger<AppController> _log;
private readonly IAppManager _appManager;
private readonly IDataManager _dataManager;
public AppController(ILogger<AppController> log, IAppManager appManager, IDataManager dataManager)
{
_log = log;
_appManager = appManager;
_dataManager = dataManager;
}
[HttpGet]
[Route("/GetApplicationNames")]
public List<string> GetApplicationNames()
{
List<string> listApplicationNames = new List<string>();
listApplicationNames = _dataManager.GetApplicationNames();
return listApplicationNames;
}
}
All you have to do to add controllers in a blazor server app is create the controller and use
AddControllers()
andMapControllers()
However your problem here is the "/" on your route attribute try
and your controller should work.