RazorPages AnchorTagHelper не удаляет индекс из href - PullRequest
0 голосов
/ 25 февраля 2020

Недавно я начал использовать RazorPages. (3.1)

В моем cs html, когда я использую:

<a asp-page="/Index">

Сгенерированный HTML:

<a href="/">

Красиво и чисто.

В тот момент, когда я ввожу пользовательскую PageRouteModelConvention (для культуры) и пользовательский AnchorTagHelper, он больше не ведет себя таким образом.

Как только мой URL начинается с культуры (domain.com/nl-BE/), ссылка на домашнюю страницу выглядит следующим образом:

<a href="/nl-BE/Index">

Хотя я бы хотел оставить ее без Индекс, как и раньше

<a href="/nl-BE">

Есть идеи, как это исправить?

Соглашение о маршруте для добавления моей культуры в URL:

    public class CultureTemplatePageRouteModelConvention : IPageRouteModelConvention
    {
        public void Apply(PageRouteModel model)
        {
            var selectorCount = model.Selectors.Count;

            for (var i = 0; i < selectorCount; i++)
            {
                var selector = model.Selectors[i];

                model.Selectors.Add(new SelectorModel
                {
                    AttributeRouteModel = new AttributeRouteModel
                    {
                        Order = -1,
                        Template = AttributeRouteModel.CombineTemplates("{culture?}", selector.AttributeRouteModel.Template),
                    }
                });
            }
        }
    }

Якорный тег по умолчанию заменяется следующим:

    [HtmlTargetElement("a", Attributes = ActionAttributeName)]
    [HtmlTargetElement("a", Attributes = ControllerAttributeName)]
    [HtmlTargetElement("a", Attributes = AreaAttributeName)]
    [HtmlTargetElement("a", Attributes = PageAttributeName)]
    [HtmlTargetElement("a", Attributes = PageHandlerAttributeName)]
    [HtmlTargetElement("a", Attributes = FragmentAttributeName)]
    [HtmlTargetElement("a", Attributes = HostAttributeName)]
    [HtmlTargetElement("a", Attributes = ProtocolAttributeName)]
    [HtmlTargetElement("a", Attributes = RouteAttributeName)]
    [HtmlTargetElement("a", Attributes = RouteValuesDictionaryName)]
    [HtmlTargetElement("a", Attributes = RouteValuesPrefix + "*")]
    public class CultureAnchorTagHelper : AnchorTagHelper
    {
        public CultureAnchorTagHelper(IHttpContextAccessor contextAccessor, IHtmlGenerator generator) :
            base(generator)
        {
            this._contextAccessor = contextAccessor;
        }

        private const string ActionAttributeName = "asp-action";
        private const string ControllerAttributeName = "asp-controller";
        private const string AreaAttributeName = "asp-area";
        private const string PageAttributeName = "asp-page";
        private const string PageHandlerAttributeName = "asp-page-handler";
        private const string FragmentAttributeName = "asp-fragment";
        private const string HostAttributeName = "asp-host";
        private const string ProtocolAttributeName = "asp-protocol";
        private const string RouteAttributeName = "asp-route";
        private const string RouteValuesDictionaryName = "asp-all-route-data";
        private const string RouteValuesPrefix = "asp-route-";
        private const string Href = "href";

        private readonly IHttpContextAccessor _contextAccessor;
        private readonly string defaultRequestCulture = "en";

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var culture = (string)_contextAccessor.HttpContext.Request.RouteValues["culture"];

            if (culture != null && culture != defaultRequestCulture)
            {
                RouteValues["culture"] = culture;
            }

            base.Process(context, output);
        }
    }

1 Ответ

0 голосов
/ 26 февраля 2020

Изменить как показано ниже:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().AddRazorPagesOptions(options =>
    {
        options.Conventions.AddFolderRouteModelConvention("/", model =>
        {
            foreach (var selector in model.Selectors)
            {
                selector.AttributeRouteModel.Template = AttributeRouteModel.CombineTemplates("{culture?}", selector.AttributeRouteModel.Template);
            }
        });
    });
    services.Configure<RequestLocalizationOptions>(options => {
        var supportedCultures = new CultureInfo[] {
        new CultureInfo("en"),
        new CultureInfo("fr")
        };

        options.DefaultRequestCulture = new RequestCulture("en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;

        options.RequestCultureProviders.Insert(0, new RouteDataRequestCultureProvider()
        {
            RouteDataStringKey = "culture",
            UIRouteDataStringKey = "culture",
            Options = options
        });
    });
    services.AddDbContext<Razor3_1Context>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("Razor3_1Context")));
}

// 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("/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();
    }

    var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(options.Value);

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

    app.UseRouting();

    app.UseAuthorization();

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

Результат: enter image description here

...