【问题标题】:Hide default action (=Index) from url on ASP.NET Core 3.1 application在 ASP.NET Core 3.1 应用程序的 url 中隐藏默认操作 (=Index)
【发布时间】:2021-08-03 08:42:32
【问题描述】:

我正在寻找一种在 ASP.NET Core 3.1 应用程序中从 url 隐藏默认操作名称的解决方案。默认操作在所有名为 Index 的控制器中,因为从 ASP.NET MCV 4 迁移到 ASP.NET Core 3.1 是在 url 中显示并在链接中配置的名称 Index。

我做了什么: 启动.cs

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace MyNamespace
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public  static IServiceCollection CmsServices { get; set; }      

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            CmsServices = services;
            services.AddResponseCompression(options =>
            {
                options.EnableForHttps = true;
            });


            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options =>
                {
                    Configuration.Bind("AzureAd", options);
                });

            services.Configure<FormOptions>(options =>
            {
                //options.BufferBody = true;
                options.KeyLengthLimit = int.MaxValue;
                options.ValueLengthLimit = int.MaxValue;
                options.ValueCountLimit = int.MaxValue;
                options.MultipartHeadersCountLimit = int.MaxValue;
                options.MultipartHeadersLengthLimit = int.MaxValue;
                options.MultipartBoundaryLengthLimit = int.MaxValue;
                options.MultipartBodyLengthLimit = int.MaxValue;
            });

            services.AddControllersWithViews(
                options =>
                    {
                        options.RespectBrowserAcceptHeader = true;
                        var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                        options.Filters.Add(new AuthorizeFilter(policy));
                    }).AddNewtonsoftJson(
                x =>
                    {
                        x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                    })
                .AddRazorRuntimeCompilation();
            services.AddLogging();
            services.AddCmsConfigurations();
            services.AddRazorPages();
            services.AddSession();
            services.AddRouting(options => options.LowercaseUrls = true);

            services.Configure<ApiBehaviorOptions>(
                options =>
                    {
                        options.SuppressModelStateInvalidFilter = true;
                    });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/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.UseStaticFiles();
            app.UseRouting();
            app.UseSession();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
            });
        }
    }
}

对于 _Layout.cshtml 中的菜单

<a class="fa fa-home" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
<a class="fa fa-home" asp-area="" asp-controller="Company" asp-action="Index">Companies</a>

根域的 url (=HomeController - Action=Index) 与预期的一样。只是没有控制器和操作名称的域。 CompanyController 操作索引的 url 是 company/index 而不是 company。

我试过跟随,但没有成功。

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();

                endpoints.MapControllerRoute("company", 
                    "{controller=Company}/{action}/{id?}",
                    defaults: new { controller = "Company", action = "Index" });

                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

我找不到解决方案。你有什么想法吗?

【问题讨论】:

    标签: routes asp.net-core-3.1


    【解决方案1】:

    我找到了一个解决方案,这个问题可能来自另一个带有 RouteAttribute 的路由配置。

    我们在 BaseController 上有属性 [Route("[controller]/[action]")]。将操作模式替换为[Route("[controller]/{action=Index}")] 后,名称索引在 url 中不再可见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2023-03-12
      • 2020-04-01
      • 2011-02-22
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多