但我需要知道什么是解决该问题的正确方法
通常,您应该使用EnableEndpointRouting
代替UseMvc
,并且可以参考更新路由启动代码以获得启用的详细步骤EnableEndpointRouting
。
为什么端点路由不需要UseMvc()函数。
对于UseMvc
,它使用the IRouter-based logic
和EnableEndpointRouting
使用endpoint-based logic
。它们遵循以下不同的逻辑:
if (options.Value.EnableEndpointRouting)
{
var mvcEndpointDataSource = app.ApplicationServices
.GetRequiredService<IEnumerable<EndpointDataSource>>()
.OfType<MvcEndpointDataSource>()
.First();
var parameterPolicyFactory = app.ApplicationServices
.GetRequiredService<ParameterPolicyFactory>();
var endpointRouteBuilder = new EndpointRouteBuilder(app);
configureRoutes(endpointRouteBuilder);
foreach (var router in endpointRouteBuilder.Routes)
{
// Only accept Microsoft.AspNetCore.Routing.Route when converting to endpoint
// Sub-types could have additional customization that we can't knowingly convert
if (router is Route route && router.GetType() == typeof(Route))
{
var endpointInfo = new MvcEndpointInfo(
route.Name,
route.RouteTemplate,
route.Defaults,
route.Constraints.ToDictionary(kvp => kvp.Key, kvp => (object)kvp.Value),
route.DataTokens,
parameterPolicyFactory);
mvcEndpointDataSource.ConventionalEndpointInfos.Add(endpointInfo);
}
else
{
throw new InvalidOperationException($"Cannot use '{router.GetType().FullName}' with Endpoint Routing.");
}
}
if (!app.Properties.TryGetValue(EndpointRoutingRegisteredKey, out _))
{
// Matching middleware has not been registered yet
// For back-compat register middleware so an endpoint is matched and then immediately used
app.UseEndpointRouting();
}
return app.UseEndpoint();
}
else
{
var routes = new RouteBuilder(app)
{
DefaultHandler = app.ApplicationServices.GetRequiredService<MvcRouteHandler>(),
};
configureRoutes(routes);
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));
return app.UseRouter(routes.Build());
}
对于EnableEndpointRouting
,它使用EndpointMiddleware将请求路由到端点。