首页 > 解决方案 > 是否可以在没有 AddMvc 的 ASP.Net Core 2.1 中创建路由映射?

问题描述

我对 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 提供的所有功能,因为我的项目不使用视图。

任何帮助将不胜感激

标签: c#asp.net-coreasp.net-core-mvcasp.net-core-2.0

解决方案


Yes . Although we often use routing with MVC , Routing is a project that has no dependencies on MVC.

When working together with ASP.NET Core , Routing works as RouterMiddleware behind the scene . If you don't want to MVC , simply build a router :

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();
}

And register the router middleware

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

Here's a screenshot when it works :

enter image description here


推荐阅读