【发布时间】:2021-10-12 12:27:15
【问题描述】:
每个人都需要做通用的 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?}");
});
}
}
}
【问题讨论】:
-
如果要在中间件中重写url,只需将
context.Request.Path改成你想要的即可。例如context.Request.Path=context.Request.Path.ToString().ToLower()
标签: asp.net-core redirect url-rewriting seo middleware