我正在开发一个项目,需要一个 Web 服务器来监听 GET 请求,其中 URL 的结构为 /function/JWT
,其中/function 是命令,/JWT 是 JSON Web token 。抛开有关这种做法的安全性的争论不谈,这就是发送者提供数据的方式。
我能够使用 System.Net.HttpServer 类构建该项目的一些其他要求,但我现在发现它在返回 400 服务器错误之前将 URL 段限制为 260 个字符之类。我无法每次部署此实用程序时都更改注册表,因此看来我可能必须尝试其他方法。
如何使用 .NET core 启动 Web 服务器来检测/function 何时是绝对路径的开头并将 JWT 交给其他代码进行解释?我拥有的一些示例 token 的长度超过 500 个字符,在其他情况下可能会更长,因此我需要更长的最大 URL 段长度。尽管对此进行了数小时的研究,但我无法找到这个看似简单问题的简单答案。
最佳答案
使用自托管 ASP.NET Core 应用程序(即,不以 IIS 或其他具有自身限制的反向代理为前端):
MaxRequestLineSize Kestrel 默认为 8192 字节,如果需要可以配置为更大的长度:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxRequestLineSize = 16000;
})
.UseStartup<Startup>();
});
}
然后您可以简单地配置一个端点来处理功能/路由:
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// 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();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/function/{jwt}", async context =>
{
var jwt = (string)context.Request.RouteValues["jwt"];
await context.Response.WriteAsync($"JWT is {jwt}, Length is {jwt.Length}");
});
});
}
}
关于c# - 如何创建 .NET Web 服务器来接收具有任意长段的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67623217/