I am trying to add a controller with routing to a Razor server-side app. I tried several things but I only see solutions for .NET 6 and cannot figure it out.
I created a controller like this:
using Microsoft.AspNetCore.Mvc;
namespace SAAR.Controllers
{
[ApiController]
[Route("settings/[controller]")]
public class ConfigurationController : ControllerBase
{
public ConfigurationController()
{
}
[HttpGet("test")]
public string Test()
{
return "Test a controller in Razor";
}
}
}
Then in my program.cs
I added:
builder.Services.AddControllers();
and
app.UseEndpoints(endpoints => {
endpoints.MapRazorPages();
endpoints.MapControllers();
});
AFAIK this should work and the endpoint http://localhost:5000/settings/test
should be there but I get a http 404 error.
What am I doing wrong?
Here my complete program.cs
:
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.EntityFrameworkCore;
using SAAR.Areas.Identity;
using SAAR.Data;
using SAAR.Services;
using SAAR.Settings;
using System.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
// Add MVC Controllers
builder.Services.AddControllers();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddTransient<IEmailSender, EmailSender>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
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.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.UseEndpoints(endpoints => {
endpoints.MapRazorPages();
endpoints.MapControllers();
});
app.Run();
Thanks for any help...
CodePudding user response:
You cannot use routing / MVC-controllers in an Razor Server web app.
CodePudding user response:
In your case,the uri should be http://localhost:5000/settings/Configuration
The name of your controller is Configuration not test
[ApiController]
[Route("settings/[controller]")]
public class ConfigurationController : ControllerBase
{
.....
}