I have an ASP.NET 5 MVC 6 application containing custom error pages. If I now want to add an API controller under the /api
path, I have seen the following pattern using the Map method:
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!");
});
}
}
The above code creates a brand new separate application under the /api
path. This is great, as you don't want custom error pages for your Web API but do want them for your MVC application.
Am I right in thinking that in the ConfigureApi, I should be adding MVC again so I can use controllers? Also, how do I configure the services, options and filters specifically for this sub-application? Is there a way to have a ConfigureServices(IServiceCollection services)
for this sub-application?
private void ConfigureApi(IApplicationBuilder app)
{
application.UseMvc();
}
Here's how you could do with a little extension method enabling "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);
};
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With