【发布时间】:2023-01-31 13:22:31
【问题描述】:
我正在尝试添加一个路由到 Razor 服务器端应用程序的控制器。我尝试了几件事,但我只看到 .NET 6 的解决方案并且无法弄清楚。
我创建了一个这样的控制器:
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";
}
}
}
然后在我的program.cs 中添加:
builder.Services.AddControllers();
和
app.UseEndpoints(endpoints => {
endpoints.MapRazorPages();
endpoints.MapControllers();
});
AFAIK 这应该可以工作并且端点 http://localhost:5000/settings/test 应该在那里,但我收到 http 404 错误。
我究竟做错了什么?
这是我完整的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();
谢谢你的帮助...
【问题讨论】:
-
尝试使用
http://localhost:5000/settings/configuration/test- 你在控制器的“基本”URL 中有[Controller]部分 - 所以它也会显示在你的 URL 中
标签: c# asp.net-core-mvc razor-pages asp.net-core-7.0