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

6

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

3
这里有一个小扩展方法可以实现“条件中间件执行”:
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
@orad 如果你正在寻找 UseWhen 的 OWIN/Katana 版本,可以随意开一个单独的问题。在这里分享链接,我会回复一个版本。 - Kévin Chalet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接