我有一个包含自定义错误页面的 ASP.NET 5 MVC 6 应用程序。如果我现在想在 /api
下添加一个 API Controller 路径,我使用 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 以便我可以使用 Controller ?另外,如何专门为此子应用程序配置服务、选项和过滤器?有没有办法拥有一个
ConfigureServices(IServiceCollection services)
对于这个子应用程序?private void ConfigureApi(IApplicationBuilder app)
{
application.UseMvc();
}
最佳答案
以下是使用启用“条件中间件执行”的小扩展方法的方法:
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);
};
});
}
}
关于asp.net-web-api - 在 ASP.NET 5 MVC 6 应用程序中使用 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31742123/