[英]asp.net core none of the controllers are initialized
我有一個 ASP.NET 項目,一切都返回 404,這是我的啟動代碼
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Home/Error");
app.UseStaticFiles();
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapGet("/debug/routes", async ctx =>
{
await ctx.Response.WriteAsync(string.Join(", ", endpoints.DataSources.SelectMany(x => x.Endpoints)));
});
});
}
}
這是一個示例 controller:
public class Home : Controller
{
private readonly DatabaseContext _databaseContext;
public Home(DatabaseContext databaseContext)
{
Console.WriteLine($"Initialized home controller"); // This doesn't get called at all.
_databaseContext = databaseContext;
_databaseContext.Database.EnsureCreated();
}
[HttpGet("/home")]
public IActionResult Index()
{
ViewData["Products"] = _databaseContext.Products.ToList();
return View();
}
.....
and whenever I launch the server it I would go to /home
and it would return 404, I also go to /debug/routes
and it would show only the 2 endpoints inside the UseEndpoints
function but never the controller classes I made
嘗試在服務中注冊您的數據庫上下文,如下所示。 由於DatabaseContext
對HomeController
的依賴無法解決,您可能會遇到錯誤。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add below line
services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connectionString));
services.AddControllersWithViews();
}
在Startup
class 的Configure(IApplicationBuilder app, IWebHostEnvironment env)
方法中,您需要類似: app.MapControllers();
我認為您的控制器已通過調用services.AddControllersWithViews();
但是沒有中間件注冊來調用你的控制器,這應該在Configure
方法中完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.