Marc Verkade
Marc Verkade

Reputation: 21

How to add controller endpoints to Razor Server in ASP.NET Core 7.0 / VS2022

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...

Upvotes: 2

Views: 2110

Answers (4)

Diego Bonfil
Diego Bonfil

Reputation: 31

I had the same problem and I couldn't call the API despite adding everything, what I found is that on the component side in the httpclient call it is necessary to add the entire route where the API is located, since for reasons of good practices it is advisable to only access external APIs, which are not on the same server.

example.

var loginResponse = await httpClient.PostAsJsonAsync<UserLogin>("https://localhost:7777/Configuration/Test", login);

Upvotes: 0

Marc Verkade
Marc Verkade

Reputation: 21

OK, figured it out, thanx!

Just create a new Razor Server project and add a folder 'Controllers' and add a C# class:ConfigurationController.cs:

using Microsoft.AspNetCore.Mvc;

namespace SAAR.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ConfigurationController : ControllerBase
    {
        public ConfigurationController()
        {
        }

        [HttpGet("[action]")]
        public string Test()
        {
            // Route: /Configuration/Test
            return "Test a controller in Razor";
        }
    }
}

In program.cs add this code and remove duplicate app.[Method] calls.

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

});

Insert this in program.cs

builder.Services.AddControllers();

So the complete program.cs looks like:

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();

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.UseEndpoints(endpoints => {
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/_Host");

});
app.Run();

Upvotes: 0

Ruikai Feng
Ruikai Feng

Reputation: 11904

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
{
 .....
}

Upvotes: 1

MartinusV
MartinusV

Reputation: 1

You cannot use routing / MVC-controllers in an Razor Server web app.

Upvotes: -2

Related Questions