在 ASP.NET 5 MVC 6 应用程序中使用 Web API

Using Web API inside a ASP.NET 5 MVC 6 Application

我有一个包含自定义错误页面的 ASP.NET 5 MVC 6 应用程序。如果我现在想在 /api 路径下添加一个 API 控制器,我已经看到使用 Map 方法的以下模式:

public class Startup
{
    public void Configure(IApplicationBuilder application)
    {
        application.Map("/api", ConfigureApi);

        application.UseStatusCodePagesWithReExecute("/error/{0}");

        application.UseMvc();
    }

    private void ConfigureApi(IApplicationBuilder application)
    {
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World from API!");
        });
    }
}

以上代码在/api路径下创建了一个全新的独立应用。这很好,因为您不希望为您的 Web API 自定义错误页面,但确实希望它们用于您的 MVC 应用程序。

我是否认为在 ConfigureApi 中我应该再次添加 MVC 以便我可以使用控制器?另外,如何专门为这个子应用程序配置服务、选项和过滤器?有没有办法让这个子应用程序有一个 ConfigureServices(IServiceCollection services)

private void ConfigureApi(IApplicationBuilder app)
{
    application.UseMvc();
}

以下是使用启用 "conditional middleware execution":

的小扩展方法的方法
public class Startup {
    public void Configure(IApplicationBuilder app) {
        app.UseWhen(context => !context.Request.Path.StartsWithSegments(new PathString("/api")), branch => {
            // Register the status code middleware, but only for non-API calls.
            branch.UseStatusCodePagesWithReExecute("/error/{0}");
        });

        app.UseMvc();
   }
}


public static class AppBuilderExtensions {
    public static IApplicationBuilder UseWhen(this IApplicationBuilder app,
        Func<HttpContext, bool> condition, Action<IApplicationBuilder> configuration) {
        if (app == null) {
            throw new ArgumentNullException(nameof(app));
        }

        if (condition == null) {
            throw new ArgumentNullException(nameof(condition));
        }

        if (configuration == null) {
            throw new ArgumentNullException(nameof(configuration));
        }

        var builder = app.New();
        configuration(builder);

        return app.Use(next => {
            builder.Run(next);

            var branch = builder.Build();

            return context => {
                if (condition(context)) {
                    return branch(context);
                }

                return next(context);
            };
        });
    }
}