【发布时间】:2022-01-03 23:27:19
【问题描述】:
我想在 .NET 6 API 项目中强制执行小写路由。
这是我的Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
这是我的WeatherForecastController.cs:
using Microsoft.AspNetCore.Mvc;
namespace Weather.API.Controllers
{
[ApiController]
[Route("weatherforecast")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
我希望只有小写的路由 (https://localhost:7243/weatherforecast) 可以工作,但是带有 pascal/大写的路由也可以工作 (https://localhost:7243/Weatherforecast)
我以为我可以添加builder.Services.AddRouting(options => options.LowercaseUrls = true); 和app.UseRouting(),但我仍然可以使用pascal/大写访问路由:https://localhost:7243/Weatherforecast。
这是我尝试过的修改后的Program.cs文件,但不起作用:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRouting(options => options.LowercaseUrls = true);
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseRouting();
app.MapControllers();
app.Run();
【问题讨论】:
-
这里的问题实际上是为什么你要强制执行区分大小写的路由? (除非你想使用 base64 的东西——这会导致无数其他问题)
-
在 SE 上也可以看到这个答案:webmasters.stackexchange.com/questions/90339/…
-
我强制执行区分大小写路由的原因是为了更严格地执行路由以防止不区分大小写的路由。我想强制执行(api/weatherforecast)但不是(Api/Weatherforecast 或 API/WEATHERFORECAST 等)
-
这实际上不是一个原因,并且 - 如果您阅读 SE 答案 - 也不是真正适用 - 我可以理解您想要它,但它为什么重要的原因
-
我的意思是:根据规范,不应该有区分大小写的路由
标签: .net-6.0