asp.net .NET Core 3.1为所有路由添加前缀

von4xj4u  于 5个月前  发布在  .NET
关注(0)|答案(2)|浏览(73)

我们的机构只允许我们一个域名(foo.bar.edu),所以我们所有的网站都被迫这样https://foo.bar.edu/Website1
我有一个.NET Core 3.1项目,我正试图让它在该网站上启动。
如果我将此添加到配置,它将工作,但默认路径也将工作。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UsePathBase("/Website1");

字符串
所以现在http://localhost:5000/Website1可以工作,而且http://localhost:5000也可以工作。
如何禁用http://localhost:5000?只有包含/Website1的路径才能工作。
这样做的真实的原因是为了方便测试生产,因为生产必须是foo.bar.edu/Website1/route/Index

gstyhher

gstyhher1#

试试下面这样的东西:

Public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    

    app.UseRouting();

    app.Map("/api", ConfigureApiRoutes); // Add a prefix to all routes

    

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers(); // Other middleware configuration
        // Other endpoint mappings
    });
}

private static void ConfigureApiRoutes(IApplicationBuilder app)
{
    app.UseEndpoints(endpoints =>
    {
        // Configure routes specific to the "/api" prefix
        endpoints.MapControllerRoute(
            name: "api_default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        
        // Other endpoint mappings specific to the "/api" prefix
    });
}

字符串

yruzcnhs

yruzcnhs2#

根据您的描述,如果您想禁用默认路径,我建议您可以考虑使用自定义中间件。
您可以构建一个自定义中间件来禁用所有不是以网站1开始的路径。
更多的细节,你可以参考下面的代码示例:

app.Use((context, next) =>
            {
                string s = context.Request.Path;
              
 (!context.Request.Path.StartsWithSegments("/Website1"))
                {
                  
                    context.Response.StatusCode = 404;
                    return Task.CompletedTask;
                }

                return next();
            });
            app.UsePathBase("/Website1");

字符串
你也可以考虑使用asp.net核心URL重写中间件来重定向/到/Website 1。
更多关于如何使用url重写中间件的细节,可以参考这个article

相关问题