【问题标题】:Using Web API inside a ASP.NET 5 MVC 6 Application在 ASP.NET 5 MVC 6 应用程序中使用 Web API
【发布时间】:2015-07-31 08:59:15
【问题描述】:

我有一个包含自定义错误页面的 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();
}

【问题讨论】:

    标签: asp.net-web-api asp.net-core asp.net-core-mvc


    【解决方案1】:

    您可以通过以下方式使用启用“条件中间件执行”的小扩展方法:

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

    【讨论】:

    • @muhammad-rehan-saeed 你成功了吗?它也应该在 MVC 5 上工作吗?
    • @orad 如果您正在寻找 UseWhen 的 OWIN/Katana 版本,请随时打开一个单独的问题。在此处分享链接,我会发布一个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多