Muh*_*eed 6 asp.net-web-api asp.net-core-mvc asp.net-core
我有一个包含自定义错误页面的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!");
});
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在/api路径下创建了一个全新的独立应用程序.这很棒,因为您不希望Web API有自定义错误页面,但确实希望它们适用于您的MVC应用程序.
我是否正确地认为在ConfigureApi中,我应该再次添加MVC以便我可以使用控制器?另外,如何针对此子应用程序专门配置服务,选项和过滤器?有没有办法ConfigureServices(IServiceCollection services)为这个子应用程序?
private void ConfigureApi(IApplicationBuilder app)
{
application.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
以下是如何使用启用“条件中间件执行”的小扩展方法:
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);
};
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
938 次 |
| 最近记录: |