【问题标题】:Default URL in net6 web appsnet6 Web 应用程序中的默认 URL
【发布时间】:2021-11-04 13:52:13
【问题描述】:

我正在将一个 net core 2.1 web 应用程序移植到 net 6,并遇到了应用程序的根 url 的问题。在 2.1 中,我在 launchSettings.json 中设置了根 url,例如

"iisExpress": {
  "applicationUrl": "http://localhost:5001/toolbox",
  "sslPort": 0
}

在引发错误的 net 6 中(applicationUrl 中不能有“/toolbox”)并且我被指示在 program.cs 中使用 app.UseBasePath,因此

var app = builder.Build();
app.UsePathBase("/toolbox");

这行得通。我可以在 localhost:5001/toolbox 上点击我的应用程序。

但我也可以在 localhost:5001 上点击它。有没有办法限制访问,让应用只响应 localhost:5001/toolbox ?

【问题讨论】:

标签: asp.net asp.net-core .net-6.0


【解决方案1】:

根据this github 讨论UsePathBase 不应该限制根路径的使用。如果你想这样做,你可以这样做:

public class RestrictingUsePathBaseMiddleware
{
    private readonly PathString pathBase;
    private readonly UsePathBaseMiddleware usePathBaseMiddleware;

    public RestrictingUsePathBaseMiddleware(RequestDelegate next, PathString pathBase)
    {
        this.pathBase = pathBase;
        usePathBaseMiddleware =new UsePathBaseMiddleware(next, pathBase);
    }

    public Task Invoke(HttpContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        if (context.Request.Path.StartsWithSegments(pathBase, out var matchedPath, out var remainingPath))
        {
            return usePathBaseMiddleware.Invoke(context);
        }

        context.Response.StatusCode = StatusCodes.Status404NotFound; // do what is appropriate with the Response
        return Task.CompletedTask;
    }
}

public static class RestrictingUsePathBaseExtensions
{
    public static IApplicationBuilder UseRestrictingPathBase(this IApplicationBuilder app, PathString pathBase)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        pathBase = pathBase.Value?.TrimEnd('/');
        if (!pathBase.HasValue)
        {
            return app;
        }

        return app.UseMiddleware<RestrictingUsePathBaseMiddleware>(pathBase);
    }
}

并将app.UsePathBase("/api");更改为app.UseRestrictingPathBase("/api");(注意,在它之前注册的所有中间件仍然会成功运行)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-18
    • 2011-08-04
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    相关资源
    最近更新 更多