首页 > 解决方案 > ASP.NET Core MVC 实施 SEO 2021

问题描述

每个人都需要做通用的 SEO 规则,但是在 ASP.NET Core MVC 中没有广泛发布的方式来:

  1. 将 http 重定向到 https
  2. 将非 www 重定向到 www
  3. 将 URL 重写为小写
  4. 删除尾随 /

在 ASP.NET 中,这些是 web.config 中的重写规则。常见的答案是在 Startup.cs 中添加以下不强制或重写的内容:

services.AddRouting(options => options.LowercaseUrls = true); services.AddRouting(options => options.AppendTrailingSlash = true);

认为最好的方法是在应用程序中添加中间件。使用,但我找不到经过验证的示例。这是我的 Startup.CS:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

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

            // CUSTOM redirect to 404 page not found
            app.Use(async (context, next) =>
            {
                await next();
                if (context.Response.StatusCode == 404)
                {
                    context.Request.Path = "/404/";
                    await next();
                }
            });

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

标签: asp.net-coreredirecturl-rewritingseomiddleware

解决方案


Github 上的Vitali Karmanov有一个很好的例子,要求 3 和 4,但不是 1 和 2。现在我只需要一个前两个规则的例子来添加到自定义 Helper。

/Helpers/RedirectLowerCaseRule.cs

    using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Net.Http.Headers;
using System.Linq;
using System.Net;

namespace Matrixforce.Helpers
{
    public class RedirectLowerCaseRule : IRule
    {
        public int StatusCode { get; } = (int)HttpStatusCode.MovedPermanently;
        public void ApplyRule(RewriteContext context)
        {
            HttpRequest request = context.HttpContext.Request;
            PathString path = context.HttpContext.Request.Path;
            PathString pathbase = context.HttpContext.Request.PathBase;
            HostString host = context.HttpContext.Request.Host;

            if ((path.HasValue && path.Value.Any(char.IsUpper)) || (host.HasValue && host.Value.Any(char.IsUpper)) || (pathbase.HasValue && pathbase.Value.Any(char.IsUpper)))
            {
                HttpResponse response = context.HttpContext.Response;
                response.StatusCode = StatusCode;
                response.Headers[HeaderNames.Location] = (request.Scheme + "://" + host.Value + request.PathBase + request.Path).ToLower() + request.QueryString;
                context.Result = RuleResult.EndResponse;
            }
            else
            {
                context.Result = RuleResult.ContinueRules;
            }
        }
    }

    public class RedirectEndingSlashCaseRule : IRule
    {
        public int StatusCode { get; } = (int)HttpStatusCode.MovedPermanently;
        public void ApplyRule(RewriteContext context)
        {
            HttpRequest request = context.HttpContext.Request;
            HostString host = context.HttpContext.Request.Host;
            string path = request.Path.ToString();

            if (path.Length > 1 && path.EndsWith("/"))
            {
                request.Path = path.Remove(path.Length - 1, 1);
                HttpResponse response = context.HttpContext.Response;
                response.StatusCode = StatusCode;
                response.Headers[HeaderNames.Location] = (request.Scheme + "://" + host.Value + request.PathBase + request.Path).ToLower() + request.QueryString;
                context.Result = RuleResult.EndResponse;
            }
            else
            {
                context.Result = RuleResult.ContinueRules;
            }
        }
    }
}

启动.cs

using Matrixforce.Helpers;

app.UseRewriter(new RewriteOptions().Add(new RedirectLowerCaseRule()).Add(new RedirectEndingSlashCaseRule()));

推荐阅读