Skip to content

Add minimal option to webapi template #36068

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/ProjectTemplates/Shared/TemplatePackageInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ private static async Task InstallTemplatePackages(ITestOutputHelper output)

await VerifyCannotFindTemplateAsync(output, "web");
await VerifyCannotFindTemplateAsync(output, "webapp");
await VerifyCannotFindTemplateAsync(output, "webapi");
await VerifyCannotFindTemplateAsync(output, "mvc");
await VerifyCannotFindTemplateAsync(output, "react");
await VerifyCannotFindTemplateAsync(output, "reactredux");
Expand All @@ -123,6 +124,7 @@ private static async Task InstallTemplatePackages(ITestOutputHelper output)

await VerifyCanFindTemplate(output, "webapp");
await VerifyCanFindTemplate(output, "web");
await VerifyCanFindTemplate(output, "webapi");
await VerifyCanFindTemplate(output, "react");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
"UseLocalDB": {
"longName": "use-local-db"
},
"UseMinimalAPIs": {
"longName": "use-minimal-apis",
"shortName": "minimal"
},
"AADInstance": {
"longName": "aad-instance",
"shortName": ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@
"invertBoolean": true,
"isVisible": true,
"defaultValue": true
},
{
"id": "UseMinimalAPIs",
"name": {
"text": "Use controllers (uncheck to use minimal APIs)"
},
"invertBoolean": true,
"isVisible": true,
"defaultValue": true
}
],
"disableHttpsSymbol": "NoHttps"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,39 @@
"exclude": [
"Properties/launchSettings.json"
]
},
{
"condition": "(UseMinimalAPIs)",
"exclude": [
"Controllers/WeatherForecastController.cs",
"Program.cs",
"WeatherForecast.cs"
]
},
{
"condition": "(UseMinimalAPIs && (NoAuth || WindowsAuth))",
"rename": {
"Program.MinimalAPIs.WindowsOrNoAuth.cs": "Program.cs"
},
"exclude": [
"Program.MinimalAPIs.OrgOrIndividualB2CAuth.cs"
]
},
{
"condition": "(UseMinimalAPIs && (IndividualAuth || OrganizationalAuth))",
"rename": {
"Program.MinimalAPIs.OrgOrIndividualB2CAuth.cs": "Program.cs"
},
"exclude": [
"Program.MinimalAPIs.WindowsOrNoAuth.cs"
]
},
{
"condition": "(UseControllers)",
"exclude": [
"Program.MinimalAPIs.WindowsOrNoAuth.cs",
"Program.MinimalAPIs.OrgOrIndividualB2CAuth.cs"
]
}
]
}
Expand Down Expand Up @@ -254,6 +287,12 @@
"defaultValue": "false",
"description": "Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual or --auth IndividualB2C is specified."
},
"UseMinimalAPIs": {
"type": "parameter",
"datatype": "bool",
"defaultValue": "false",
"description": "Whether to use mininmal APIs instead of controllers."
},
"Framework": {
"type": "parameter",
"description": "The target framework for the project.",
Expand Down Expand Up @@ -321,6 +360,10 @@
"EnableOpenAPI": {
"type": "computed",
"value": "(!DisableOpenAPI)"
},
"UseControllers": {
"type": "computed",
"value": "(!UseMinimalAPIs)"
}
},
"primaryOutputs": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,15 @@ public class WeatherForecastController : ControllerBase
public WeatherForecastController(ILogger<WeatherForecastController> logger,
IDownstreamWebApi downstreamWebApi)
{
_logger = logger;
_logger = logger;
_downstreamWebApi = downstreamWebApi;
}

#if (EnableOpenAPI)
[HttpGet(Name = "GetWeatherForecast")]
#else
[HttpGet]
#endif
public async Task<IEnumerable<WeatherForecast>> Get()
{
using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);
Expand Down Expand Up @@ -74,11 +78,15 @@ public async Task<IEnumerable<WeatherForecast>> Get()
public WeatherForecastController(ILogger<WeatherForecastController> logger,
GraphServiceClient graphServiceClient)
{
_logger = logger;
_logger = logger;
_graphServiceClient = graphServiceClient;
}

#if (EnableOpenAPI)
[HttpGet(Name = "GetWeatherForecast")]
#else
[HttpGet]
#endif
public async Task<IEnumerable<WeatherForecast>> Get()
{
var user = await _graphServiceClient.Me.Request().GetAsync();
Expand All @@ -97,7 +105,11 @@ public WeatherForecastController(ILogger<WeatherForecastController> logger)
_logger = logger;
}

#if (EnableOpenAPI)
[HttpGet(Name = "GetWeatherForecast")]
#else
[HttpGet]
#endif
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
#if (GenerateApi)
using System.Net.Http;
#endif
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
#if (GenerateGraph)
using Graph = Microsoft.Graph;
#endif
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
#if (OrganizationalAuth)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
#if (GenerateApiOrGraph)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
#if (GenerateApi)
.AddDownstreamWebApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
#endif
#if (GenerateGraph)
.AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi"))
#endif
.AddInMemoryTokenCaches();
#else
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
#endif
#elif (IndividualB2CAuth)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
#if (GenerateApi)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddDownstreamWebApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
#else
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));
#endif
#endif
builder.Services.AddAuthorization();

#if (EnableOpenAPI)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#endif

var app = builder.Build();

// Configure the HTTP request pipeline.
#if (EnableOpenAPI)
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
#endif
#if (RequiresHttps)

app.UseHttpsRedirection();
#endif

app.UseAuthentication();
app.UseAuthorization();

var scopeRequiredByApi = app.Configuration["AzureAd:Scopes"];
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

#if (GenerateApi)
app.MapGet("/weatherforecast", (HttpContext httpContext, IDownstreamWebApi downstreamWebApi) =>
{
httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

using var response = await downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// Do something
}
else
{
var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
}

var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();

return forecast;
})
#elseif (GenerateGraph)
app.MapGet("/weahterforecast", (HttpContext httpContext, GraphServiceClient graphServiceClient) =>
{
httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

var user = await _graphServiceClient.Me.Request().GetAsync();

var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();

return forecast;
})
#else
app.MapGet("/weatherforecast", (HttpContext httpContext) =>
{
httpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
#endif
#if (EnableOpenAPI)
})
.WithName("GetWeatherForecast")
.RequireAuthorization();
#else
})
.RequireAuthorization();
#endif

app.Run();

record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
#if (EnableOpenAPI)
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
#endif

var app = builder.Build();

// Configure the HTTP request pipeline.
#if (EnableOpenAPI)
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
#endif
#if (RequiresHttps)

app.UseHttpsRedirection();
#endif

var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateTime.Now.AddDays(index),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
#if (EnableOpenAPI)
})
.WithName("GetWeatherForecast");
#else
});
#endif

app.Run();

record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
2 changes: 2 additions & 0 deletions src/ProjectTemplates/scripts/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ angular/
blazorserver/
blazorwasm/
mvc/
mvcorgauth/
razor/
react/
reactredux/
web/
webapp/
webapi/
webapimin/
worker/
grpc/
12 changes: 12 additions & 0 deletions src/ProjectTemplates/scripts/Run-WebApiMinimal-Locally.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env pwsh
#requires -version 4

[CmdletBinding(PositionalBinding = $false)]
param()

Set-StrictMode -Version 2
$ErrorActionPreference = 'Stop'

. $PSScriptRoot\Test-Template.ps1

Test-Template "webapimin" "webapi -minimal" "Microsoft.DotNet.Web.ProjectTemplates.6.0.6.0.0-dev.nupkg" $false
Loading