.NET Core-为控制器设置自定义路由URL



场景-而不是将控制器路由到

localhost:5555/home/menu

(主页=>主控制器和菜单=>操作(,

我想将API路由到类似的东西

localhost:5555/abc/xyz/mnop/ert/home/menu

我使用

app.UsePathBase(new PathString("/abc/xyz/mnop/ert"));
app.UseRouting();

但是API在CCD_ 1和CCD_但是,它应该在localhost:5555/abc/xyz/mnop/ert/home/menu上响应200,在localhost:5555/home/menu上响应404。

浏览并发现存在问题UsePathBase未禁用根路径报告并在没有具体响应的情况下关闭。

我不想实现任何自定义中间件,因为它会影响应用程序的性能。有其他方法吗?

我建议您可以重写像UsePathBase中间件这样的中间件,并在其中放入一些自定义逻辑。UsePathBase源代码如下:

public class UsePathBaseMiddleware
{
private readonly RequestDelegate _next;
private readonly PathString _pathBase;
/// <summary>
/// Creates a new instance of <see cref="UsePathBaseMiddleware"/>.
/// </summary>
/// <param name="next">The delegate representing the next middleware in the request pipeline.</param>
/// <param name="pathBase">The path base to extract.</param>
public UsePathBaseMiddleware(RequestDelegate next, PathString pathBase)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (!pathBase.HasValue)
{
throw new ArgumentException($"{nameof(pathBase)} cannot be null or empty.");
}
_next = next;
_pathBase = pathBase;
}
/// <summary>
/// Executes the middleware.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <returns>A task that represents the execution of this middleware.</returns>
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 InvokeCore(context, matchedPath, remainingPath);
}
return _next(context);
}
private async Task InvokeCore(HttpContext context, PathString matchedPath, PathString remainingPath)
{
var originalPath = context.Request.Path;
var originalPathBase = context.Request.PathBase;
context.Request.Path = remainingPath;
context.Request.PathBase = originalPathBase.Add(matchedPath);
try
{
await _next(context);
}
finally
{
context.Request.Path = originalPath;
context.Request.PathBase = originalPathBase;
}
}
}

下面是它的扩展方法:

public static IApplicationBuilder UsePathBase(this IApplicationBuilder app, PathString pathBase)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
// Strip trailing slashes
pathBase = new PathString(pathBase.Value?.TrimEnd('/'));
if (!pathBase.HasValue)
{
return app;
}
// Only use this path if there's a global router (in the 'WebApplication' case).
if (app.Properties.TryGetValue(RerouteHelper.GlobalRouteBuilderKey, out var routeBuilder) && routeBuilder is not null)
{
return app.Use(next =>
{
var newNext = RerouteHelper.Reroute(app, routeBuilder, next);
return new UsePathBaseMiddleware(newNext, pathBase).Invoke;
});
}
return app.UseMiddleware<UsePathBaseMiddleware>(pathBase);
}

最新更新