asp.net-core - ASP.NET Core MVC 实施 SEO 2021
问题描述
每个人都需要做通用的 SEO 规则,但是在 ASP.NET Core MVC 中没有广泛发布的方式来:
- 将 http 重定向到 https
- 将非 www 重定向到 www
- 将 URL 重写为小写
- 删除尾随 /
在 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?}");
});
}
}
}
解决方案
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()));
推荐阅读
- android - 从 CMake 获取并构建 libpng-android
- tcl - Tcl 过程如何访问它之外的几十个常量?
- csv - csv 中的 Hive 结果
- android - 将底部卡片视图转换为顶部卡片视图
- elasticsearch - fluent-bit 无法解析 kubernetes 日志
- javascript - Do i need to print PHP form validation Errors to user?
- javascript - 为什么这个 POST 方法没有在 Node 的 Postgres 数据库中插入数据?
- html - 我在移动设备上的页脚被页面截断
- python - 在具有 w1、w2 等周数的索引上尝试 Sort_Index,但它不起作用?
- azure - 尝试调用 B2C 登录时 Cors no-access-control-allow-origin