簡體   English   中英

如何在 ASP.NET Core 2.1 中使用“MapControllers”

[英]How to use 'MapControllers' in ASP.NET Core 2.1

請參閱ASP.NET 內核中的路由到 controller 操作

此文檔頁面可以切換到 2.1。 它顯示屬性路由指令。

但是,像app.UseEndpoints(()=>)endpoints.MapControllers();這樣的方法app.MapControllers(); 在我的環境中不存在。

我已經安裝了這些軟件包:

Microsoft.AspNetCore.Hosting
Microsoft.AspNetCore.Http
Microsoft.AspNetCore.Mvc
Microsoft.AspNetCore.Routing
Microsoft.AspNetCore.Routing.Abstractions

我還應該安裝什么?

但是,像 app.UseEndpoints(()=>)、endpoints.MapControllers(); 這樣的方法或 app.MapControllers(); 在我的環境中不存在。

這是一個文檔問題,端點路由適用於 ASP.NET Core 3.0 及更高版本,而不是 Asp.net Core 2.1

在 Asp.net 核心 2.1 MVC 應用程序中,您應該使用UseMvc中間件和MapRoute()方法,startup.cs 文件如下所示:

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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

如果您想使用端點路由,您可以將應用程序從 Asp.net 核心 2.1 遷移到 Asp.net 核心 3.1。 請參閱此鏈接和步驟

對於文檔問題,您可以通過單擊文檔末尾的按鈕提交反饋:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM