【问题标题】:Is it possible to create a route mapping in ASP.Net Core 2.1 without AddMvc?是否可以在没有 AddMvc 的 ASP.Net Core 2.1 中创建路由映射?
【发布时间】:2023-03-06 05:50:01
【问题描述】:

我对 ASP.NET Core 完全陌生,我搜索了很多,但仍然对 Core 2.1 中的路由感到困惑。

所以,我创建了一个示例项目,选择 API 作为模板,VS 创建了如下内容:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc();

    }

但我不需要 MVC 提供的所有功能,因为我的项目不使用视图。

任何帮助将不胜感激

【问题讨论】:

  • 您可以简单地使用services.AddMvcCore,然后只添加您真正需要的服务。 app.UseMvc 部分只是放入已注册的中间件中,因此您不需要在那里做任何特别的事情。尽管有这个名字,但它不仅仅是 MVC 特定的,所以你仍然需要以某种形式调用。
  • 我鼓励你去看看每一个的来源。在那里您将能够看到每个调用实际上正在执行的操作,即服务AddMvc 注册与AddMvcCoregithub.com/aspnet/Mvc
  • @ChrisPratt 感谢您的建议。我查看了 AddMvc,发现了不需要的东西(剃刀视图等)。

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.0


【解决方案1】:

是的。虽然我们经常在 MVC 中使用路由,但 Routing 是一个不依赖于 MVC 的项目。

当与 ASP.NET Core 一起工作时,路由在幕后充当 RouterMiddleware。如果您不想 MVC,只需构建一个路由器:

private IRouter BuildRouter(IApplicationBuilder applicationBuilder)
{
    var builder = new RouteBuilder(applicationBuilder);

    // use middlewares to configure a route
    builder.MapMiddlewareGet("/api/hello", appBuilder => {
        appBuilder.Use(async (context,next) => {
            context.Response.Headers["H1"] = "Hello1";
            await next();
        });
        appBuilder.Use(async (context,next) => {
            context.Response.Headers["H2"] = "Hello2";
            await next();
        });
        appBuilder.Run(async (context) => {
            await context.Response.WriteAsync("Hello,world");
        });

    });

    builder.MapMiddlewarePost("/api/hello", appBuilder => {
        // ...
    });

    // ....

    return builder.Build();
}

并注册路由器中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...
    app.UseRouter(BuildRouter(app));
}

这是一个运行时的屏幕截图:

【讨论】:

  • 好极了!不知道这是可能的。
  • 它是否像经典的 WebAPIConfig 一样使用默认路由? config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
  • @MickMarosky 。 WebApi 模板使用带有默认路由的 MVC。但是,如上所述,如果您选择使用Routing 而不使用MvcRouting 如何实现控制器或动作?您是否尝试创建没有视图的 WebApi 项目?
  • @itminus 是的,我的项目不会使用视图。
  • @MickMarosky 我想知道如果您想要将请求调度到 MVC 操作的默认路由器行为,为什么不使用 WebApi 模板?
【解决方案2】:

是的。来自https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.1

var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

routeBuilder.MapGet("hello/{name}", context => {
    var name = context.GetRouteValue("name");
    return context.Response.WriteAsync($"Hi, {name}!"); });            

var routes = routeBuilder.Build(); app.UseRouter(routes);

或者如果您想将其实现为自定义中间件并且您只需要基本路由:

发件人:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1

public class Startup
{
    private static void HandleMapTest1(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Map Test 1");
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Map("/map1", HandleMapTest1);

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from non-Map delegate. <p>");
        });
    }
}

或者如果你需要更多的路由功能,看itmius的回答https://stackoverflow.com/a/52377807/2085502

【讨论】:

    【解决方案3】:

    已解决,使用以下启动:

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                .AddApiExplorer()
                .AddAuthorization()
                .AddJsonFormatters()
                .AddCors();
    }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseMvc();
    }
    

    感谢所有试图帮助我的人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 2019-08-18
      • 1970-01-01
      相关资源
      最近更新 更多