Действие не отображается пользовательским маршрутизатором в веб-API ASP.NET Core 8.C#

Место общения программистов C#
Anonymous
Действие не отображается пользовательским маршрутизатором в веб-API ASP.NET Core 8.

Сообщение Anonymous »

В моем проекте веб-API ASP.NET Core 8, написанном на C#, нам нужно направить указанные ниже конечные точки к одному методу действия с настраиваемым маршрутом в API.
Вот мой код - CustomRouter:

Код: Выделить всё

public class CustomRouter : IRouter
{
private readonly IRouter _defaultRouter;

public CustomRouter(IRouter defaultRouter)
{
_defaultRouter = defaultRouter;
}

public async Task RouteAsync(RouteContext context)
{
// Extract the path and query string from the request
var path = context.HttpContext.Request.Path.Value;
var queryString = context.HttpContext.Request.QueryString;

// Split the path into segments to extract controller name and entity name
var pathSegments = path.Split('/');
var controllerName = pathSegments.Length > 1 ? pathSegments[pathSegments.Length - 2] : string.Empty;
var entityName = pathSegments.Length > 0 ? pathSegments[pathSegments.Length - 1] : string.Empty;
var queryParameters = queryString.HasValue ? queryString.Value : string.Empty;

// Check if the request is a GET request and targeting the InsightsController
if (controllerName.Equals("insights", StringComparison.OrdinalIgnoreCase) &&
context.HttpContext.Request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase))
{
// Set RouteData for controller and action
context.RouteData.Values["controller"] = "Insights";
context.RouteData.Values["action"] = "GetTest"; // The action method to invoke
context.RouteData.Values["entity"] = entityName; // Pass entity name
context.RouteData.Values["queryParameters"] = queryParameters; // Pass query parameters if needed

context.HttpContext.Request.Path = new PathString("/api/v1/Insights/");
context.HttpContext.Request.QueryString = new QueryString();
// Pass the request to the default router or the next middleware, which will handle invoking the controller
await _defaultRouter.RouteAsync(context);
return;
}

// If no match is found, delegate to the next middleware
await _defaultRouter.RouteAsync(context);
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
// Generate virtual path if needed
return _defaultRouter.GetVirtualPath(context);
}
}
Добавьте использование пользовательского маршрутизатора в классе Startup:

Код: Выделить всё

// Use Custom Router
app.UseRouter(builder =>
{
// Create default router to pass to CustomRouter
var defaultRouter = builder.Build();

// Register the CustomRouter
builder.Routes.Add(new CustomRouter(defaultRouter));
});
Класс контроллера:

Код: Выделить всё

[Route("api/v1/[controller]")]
[ApiController]
public class InsightsController : Controller
{
[HttpGet]
public async Task Get(string entity, string id = default)
{
}
}
Добавлен собственный маршрутизатор. Несмотря на наличие пользовательского маршрутизатора,
Метод Get контроллера Insights сопоставляется и выполняется для этого запроса

Код: Выделить всё

http://localhost:63896/api/v1/Insights
Но не для запроса ниже

Код: Выделить всё

http://localhost:63896/api/v1/Insights/pdrsearch?rs:q=bug
Поискал в Google любую справку/пример кода, а также попробовал добавить пользовательское промежуточное ПО.
Пока безуспешно.

Подробнее здесь: https://stackoverflow.com/questions/790 ... -8-web-api

Вернуться в «C#»