diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Areas/Identity/RevalidatingIdentityAuthenticationStateProvider.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Areas/Identity/RevalidatingIdentityAuthenticationStateProvider.cs index f930d612fd3d..f210b2eebe6c 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Areas/Identity/RevalidatingIdentityAuthenticationStateProvider.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Areas/Identity/RevalidatingIdentityAuthenticationStateProvider.cs @@ -5,66 +5,65 @@ using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; -namespace BlazorServerWeb_CSharp.Areas.Identity +namespace BlazorServerWeb_CSharp.Areas.Identity; + +public class RevalidatingIdentityAuthenticationStateProvider + : RevalidatingServerAuthenticationStateProvider where TUser : class { - public class RevalidatingIdentityAuthenticationStateProvider - : RevalidatingServerAuthenticationStateProvider where TUser : class + private readonly IServiceScopeFactory _scopeFactory; + private readonly IdentityOptions _options; + + public RevalidatingIdentityAuthenticationStateProvider( + ILoggerFactory loggerFactory, + IServiceScopeFactory scopeFactory, + IOptions optionsAccessor) + : base(loggerFactory) { - private readonly IServiceScopeFactory _scopeFactory; - private readonly IdentityOptions _options; + _scopeFactory = scopeFactory; + _options = optionsAccessor.Value; + } - public RevalidatingIdentityAuthenticationStateProvider( - ILoggerFactory loggerFactory, - IServiceScopeFactory scopeFactory, - IOptions optionsAccessor) - : base(loggerFactory) + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30); + + protected override async Task ValidateAuthenticationStateAsync( + AuthenticationState authenticationState, CancellationToken cancellationToken) + { + // Get the user manager from a new scope to ensure it fetches fresh data + var scope = _scopeFactory.CreateScope(); + try { - _scopeFactory = scopeFactory; - _options = optionsAccessor.Value; + var userManager = scope.ServiceProvider.GetRequiredService>(); + return await ValidateSecurityStampAsync(userManager, authenticationState.User); } - - protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30); - - protected override async Task ValidateAuthenticationStateAsync( - AuthenticationState authenticationState, CancellationToken cancellationToken) + finally { - // Get the user manager from a new scope to ensure it fetches fresh data - var scope = _scopeFactory.CreateScope(); - try + if (scope is IAsyncDisposable asyncDisposable) { - var userManager = scope.ServiceProvider.GetRequiredService>(); - return await ValidateSecurityStampAsync(userManager, authenticationState.User); + await asyncDisposable.DisposeAsync(); } - finally + else { - if (scope is IAsyncDisposable asyncDisposable) - { - await asyncDisposable.DisposeAsync(); - } - else - { - scope.Dispose(); - } + scope.Dispose(); } } + } - private async Task ValidateSecurityStampAsync(UserManager userManager, ClaimsPrincipal principal) + private async Task ValidateSecurityStampAsync(UserManager userManager, ClaimsPrincipal principal) + { + var user = await userManager.GetUserAsync(principal); + if (user == null) { - var user = await userManager.GetUserAsync(principal); - if (user == null) - { - return false; - } - else if (!userManager.SupportsUserSecurityStamp) - { - return true; - } - else - { - var principalStamp = principal.FindFirstValue(_options.ClaimsIdentity.SecurityStampClaimType); - var userStamp = await userManager.GetSecurityStampAsync(user); - return principalStamp == userStamp; - } + return false; + } + else if (!userManager.SupportsUserSecurityStamp) + { + return true; + } + else + { + var principalStamp = principal.FindFirstValue(_options.ClaimsIdentity.SecurityStampClaimType); + var userStamp = await userManager.GetSecurityStampAsync(user); + return principalStamp == userStamp; } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/ApplicationDbContext.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/ApplicationDbContext.cs index b8b1d8434a01..8c40085e8769 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/ApplicationDbContext.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/ApplicationDbContext.cs @@ -1,13 +1,12 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; -namespace BlazorServerWeb_CSharp.Data +namespace BlazorServerWeb_CSharp.Data; + +public class ApplicationDbContext : IdentityDbContext { - public class ApplicationDbContext : IdentityDbContext + public ApplicationDbContext(DbContextOptions options) + : base(options) { - public ApplicationDbContext(DbContextOptions options) - : base(options) - { - } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecast.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecast.cs index c9b3052b7581..5badb0fae437 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecast.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecast.cs @@ -1,13 +1,12 @@ -namespace BlazorServerWeb_CSharp.Data +namespace BlazorServerWeb_CSharp.Data; + +public class WeatherForecast { - public class WeatherForecast - { - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public int TemperatureC { get; set; } + public int TemperatureC { get; set; } - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - public string? Summary { get; set; } - } + public string? Summary { get; set; } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs index 4cdc4e4e3cca..3b0a57f218ae 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Data/WeatherForecastService.cs @@ -1,20 +1,19 @@ -namespace BlazorServerWeb_CSharp.Data +namespace BlazorServerWeb_CSharp.Data; + +public class WeatherForecastService { - public class WeatherForecastService + private static readonly string[] Summaries = new[] { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; - public Task GetForecastAsync(DateTime startDate) + public Task GetForecastAsync(DateTime startDate) + { + return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast { - return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = startDate.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }).ToArray()); - } + Date = startDate.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }).ToArray()); } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Pages/Error.cshtml.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Pages/Error.cshtml.cs index 230136caaf33..30f9102b469a 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Pages/Error.cshtml.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/BlazorServerWeb-CSharp/Pages/Error.cshtml.cs @@ -2,26 +2,25 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace BlazorServerWeb_CSharp.Pages +namespace BlazorServerWeb_CSharp.Pages; + +[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] +[IgnoreAntiforgeryToken] +public class ErrorModel : PageModel { - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - [IgnoreAntiforgeryToken] - public class ErrorModel : PageModel - { - public string? RequestId { get; set; } + public string? RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger; + private readonly ILogger _logger; - public ErrorModel(ILogger logger) - { - _logger = logger; - } + public ErrorModel(ILogger logger) + { + _logger = logger; + } - public void OnGet() - { - RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() + { + RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/OidcConfigurationController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/OidcConfigurationController.cs index c279b40060a8..cf71c627637a 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/OidcConfigurationController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/OidcConfigurationController.cs @@ -1,25 +1,24 @@ using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; using Microsoft.AspNetCore.Mvc; -namespace ComponentsWebAssembly_CSharp.Server.Controllers +namespace ComponentsWebAssembly_CSharp.Server.Controllers; + +public class OidcConfigurationController : Controller { - public class OidcConfigurationController : Controller - { - private readonly ILogger _logger; + private readonly ILogger _logger; - public OidcConfigurationController(IClientRequestParametersProvider clientRequestParametersProvider, ILogger logger) - { - ClientRequestParametersProvider = clientRequestParametersProvider; - _logger = logger; - } + public OidcConfigurationController(IClientRequestParametersProvider clientRequestParametersProvider, ILogger logger) + { + ClientRequestParametersProvider = clientRequestParametersProvider; + _logger = logger; + } - public IClientRequestParametersProvider ClientRequestParametersProvider { get; } + public IClientRequestParametersProvider ClientRequestParametersProvider { get; } - [HttpGet("_configuration/{clientId}")] - public IActionResult GetClientRequestParameters([FromRoute]string clientId) - { - var parameters = ClientRequestParametersProvider.GetClientParameters(HttpContext, clientId); - return Ok(parameters); - } + [HttpGet("_configuration/{clientId}")] + public IActionResult GetClientRequestParameters([FromRoute]string clientId) + { + var parameters = ClientRequestParametersProvider.GetClientParameters(HttpContext, clientId); + return Ok(parameters); } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs index 46dd2a8b2f37..2d3a3e2a8c1d 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Controllers/WeatherForecastController.cs @@ -14,108 +14,107 @@ #endif using ComponentsWebAssembly_CSharp.Shared; -namespace ComponentsWebAssembly_CSharp.Server.Controllers -{ +namespace ComponentsWebAssembly_CSharp.Server.Controllers; + #if (!NoAuth) - [Authorize] +[Authorize] #endif - [ApiController] - [Route("[controller]")] - public class WeatherForecastController : ControllerBase +[ApiController] +[Route("[controller]")] +public class WeatherForecastController : ControllerBase +{ + private static readonly string[] Summaries = new[] { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; - private readonly ILogger _logger; + private readonly ILogger _logger; #if (OrganizationalAuth || IndividualB2CAuth) - // The Web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API - static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; + // The Web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API + static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; #endif #if (GenerateApi) - private readonly IDownstreamWebApi _downstreamWebApi; + private readonly IDownstreamWebApi _downstreamWebApi; + + public WeatherForecastController(ILogger logger, + IDownstreamWebApi downstreamWebApi) + { + _logger = logger; + _downstreamWebApi = downstreamWebApi; + } + + [HttpGet] + public async Task> Get() + { + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); - public WeatherForecastController(ILogger logger, - IDownstreamWebApi downstreamWebApi) + using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) { - _logger = logger; - _downstreamWebApi = downstreamWebApi; + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + // Do something } - - [HttpGet] - public async Task> Get() + else { - 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}"); - } - - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } -#elseif (GenerateGraph) - private readonly GraphServiceClient _graphServiceClient; - - public WeatherForecastController(ILogger logger, - GraphServiceClient graphServiceClient) + return Enumerable.Range(1, 5).Select(index => new WeatherForecast { - _logger = logger; - _graphServiceClient = graphServiceClient; - } + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } - [HttpGet] - public async Task> Get() - { - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); - var user = await _graphServiceClient.Me.Request().GetAsync(); +#elseif (GenerateGraph) + private readonly GraphServiceClient _graphServiceClient; - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } -#else - public WeatherForecastController(ILogger logger) - { + public WeatherForecastController(ILogger logger, + GraphServiceClient graphServiceClient) + { _logger = logger; - } + _graphServiceClient = graphServiceClient; + } + + [HttpGet] + public async Task> Get() + { + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); + var user = await _graphServiceClient.Me.Request().GetAsync(); - [HttpGet] - public IEnumerable Get() + return Enumerable.Range(1, 5).Select(index => new WeatherForecast { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } +#else + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { #if (OrganizationalAuth || IndividualB2CAuth) - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); #endif - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } -#endif + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); } +#endif } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Data/ApplicationDbContext.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Data/ApplicationDbContext.cs index 26ed9ba32ace..39ef8cb3a4e7 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Data/ApplicationDbContext.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Data/ApplicationDbContext.cs @@ -4,14 +4,13 @@ using IdentityServer4.EntityFramework.Options; using ComponentsWebAssembly_CSharp.Server.Models; -namespace ComponentsWebAssembly_CSharp.Server.Data +namespace ComponentsWebAssembly_CSharp.Server.Data; + +public class ApplicationDbContext : ApiAuthorizationDbContext { - public class ApplicationDbContext : ApiAuthorizationDbContext + public ApplicationDbContext( + DbContextOptions options, + IOptions operationalStoreOptions) : base(options, operationalStoreOptions) { - public ApplicationDbContext( - DbContextOptions options, - IOptions operationalStoreOptions) : base(options, operationalStoreOptions) - { - } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Models/ApplicationUser.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Models/ApplicationUser.cs index 25fb8e993271..495fab022817 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Models/ApplicationUser.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Models/ApplicationUser.cs @@ -1,8 +1,7 @@ using Microsoft.AspNetCore.Identity; -namespace ComponentsWebAssembly_CSharp.Server.Models +namespace ComponentsWebAssembly_CSharp.Server.Models; + +public class ApplicationUser : IdentityUser { - public class ApplicationUser : IdentityUser - { - } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Pages/Error.cshtml.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Pages/Error.cshtml.cs index ae2531630485..6c94b7091de2 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Pages/Error.cshtml.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Server/Pages/Error.cshtml.cs @@ -2,26 +2,25 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace ComponentsWebAssembly_CSharp.Server.Pages +namespace ComponentsWebAssembly_CSharp.Server.Pages; + +[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] +[IgnoreAntiforgeryToken] +public class ErrorModel : PageModel { - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - [IgnoreAntiforgeryToken] - public class ErrorModel : PageModel - { - public string? RequestId { get; set; } + public string? RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger; + private readonly ILogger _logger; - public ErrorModel(ILogger logger) - { - _logger = logger; - } + public ErrorModel(ILogger logger) + { + _logger = logger; + } - public void OnGet() - { - RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() + { + RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Shared/WeatherForecast.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Shared/WeatherForecast.cs index 3e26a36fdfc9..7ea4cac0e5b1 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Shared/WeatherForecast.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/ComponentsWebAssembly-CSharp/Shared/WeatherForecast.cs @@ -1,13 +1,12 @@ -namespace ComponentsWebAssembly_CSharp.Shared +namespace ComponentsWebAssembly_CSharp.Shared; + +public class WeatherForecast { - public class WeatherForecast - { - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public int TemperatureC { get; set; } + public int TemperatureC { get; set; } - public string? Summary { get; set; } + public string? Summary { get; set; } - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - } + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/GrpcService-CSharp/Services/GreeterService.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/GrpcService-CSharp/Services/GreeterService.cs index 39c967545928..37efaff8dc95 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/GrpcService-CSharp/Services/GreeterService.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/GrpcService-CSharp/Services/GreeterService.cs @@ -1,22 +1,21 @@ using Grpc.Core; using GrpcService_CSharp; -namespace GrpcService_CSharp.Services +namespace GrpcService_CSharp.Services; + +public class GreeterService : Greeter.GreeterBase { - public class GreeterService : Greeter.GreeterBase + private readonly ILogger _logger; + public GreeterService(ILogger logger) { - private readonly ILogger _logger; - public GreeterService(ILogger logger) - { - _logger = logger; - } + _logger = logger; + } - public override Task SayHello(HelloRequest request, ServerCallContext context) + public override Task SayHello(HelloRequest request, ServerCallContext context) + { + return Task.FromResult(new HelloReply { - return Task.FromResult(new HelloReply - { - Message = "Hello " + request.Name - }); - } + Message = "Hello " + request.Name + }); } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/Areas/MyFeature/Pages/Page1.cshtml.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/Areas/MyFeature/Pages/Page1.cshtml.cs index 4bc36c20a93a..e3eaf04603e0 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/Areas/MyFeature/Pages/Page1.cshtml.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/Areas/MyFeature/Pages/Page1.cshtml.cs @@ -1,13 +1,12 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace Company.RazorClassLibrary1.MyFeature.Pages +namespace Company.RazorClassLibrary1.MyFeature.Pages; + +public class Page1Model : PageModel { - public class Page1Model : PageModel + public void OnGet() { - public void OnGet() - { - } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/ExampleJsInterop.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/ExampleJsInterop.cs index 500703f77222..208edd84ede3 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/ExampleJsInterop.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorClassLibrary-CSharp/ExampleJsInterop.cs @@ -1,37 +1,36 @@ using Microsoft.JSInterop; -namespace Company.RazorClassLibrary1 +namespace Company.RazorClassLibrary1; + +// This class provides an example of how JavaScript functionality can be wrapped +// in a .NET class for easy consumption. The associated JavaScript module is +// loaded on demand when first needed. +// +// This class can be registered as scoped DI service and then injected into Blazor +// components for use. + +public class ExampleJsInterop : IAsyncDisposable { - // This class provides an example of how JavaScript functionality can be wrapped - // in a .NET class for easy consumption. The associated JavaScript module is - // loaded on demand when first needed. - // - // This class can be registered as scoped DI service and then injected into Blazor - // components for use. + private readonly Lazy> moduleTask; - public class ExampleJsInterop : IAsyncDisposable + public ExampleJsInterop(IJSRuntime jsRuntime) { - private readonly Lazy> moduleTask; + moduleTask = new (() => jsRuntime.InvokeAsync( + "import", "./_content/Company.RazorClassLibrary1/exampleJsInterop.js").AsTask()); + } - public ExampleJsInterop(IJSRuntime jsRuntime) - { - moduleTask = new (() => jsRuntime.InvokeAsync( - "import", "./_content/Company.RazorClassLibrary1/exampleJsInterop.js").AsTask()); - } + public async ValueTask Prompt(string message) + { + var module = await moduleTask.Value; + return await module.InvokeAsync("showPrompt", message); + } - public async ValueTask Prompt(string message) + public async ValueTask DisposeAsync() + { + if (moduleTask.IsValueCreated) { var module = await moduleTask.Value; - return await module.InvokeAsync("showPrompt", message); - } - - public async ValueTask DisposeAsync() - { - if (moduleTask.IsValueCreated) - { - var module = await moduleTask.Value; - await module.DisposeAsync(); - } + await module.DisposeAsync(); } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Data/ApplicationDbContext.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Data/ApplicationDbContext.cs index d883b6ecc1f8..4e8fb8cbf43a 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Data/ApplicationDbContext.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Data/ApplicationDbContext.cs @@ -1,13 +1,12 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; -namespace Company.WebApplication1.Data +namespace Company.WebApplication1.Data; + +public class ApplicationDbContext : IdentityDbContext { - public class ApplicationDbContext : IdentityDbContext + public ApplicationDbContext(DbContextOptions options) + : base(options) { - public ApplicationDbContext(DbContextOptions options) - : base(options) - { - } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Error.cshtml.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Error.cshtml.cs index 631c911ffae0..f13301ac31d6 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Error.cshtml.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Error.cshtml.cs @@ -2,26 +2,26 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace Company.WebApplication1.Pages +namespace Company.WebApplication1.Pages; + +[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] +[IgnoreAntiforgeryToken] +public class ErrorModel : PageModel { - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - [IgnoreAntiforgeryToken] - public class ErrorModel : PageModel - { - public string? RequestId { get; set; } + public string? RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger _logger; + private readonly ILogger _logger; - public ErrorModel(ILogger logger) - { - _logger = logger; - } + public ErrorModel(ILogger logger) + { + _logger = logger; + } - public void OnGet() - { - RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; - } + public void OnGet() + { + RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Index.cshtml.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Index.cshtml.cs index 87d7e464a0a1..af4794371e82 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Index.cshtml.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Index.cshtml.cs @@ -10,65 +10,64 @@ using Microsoft.Identity.Web; #endif -namespace Company.WebApplication1.Pages -{ +namespace Company.WebApplication1.Pages; + #if (GenerateApiOrGraph) - [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")] +[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")] #endif - public class IndexModel : PageModel - { - private readonly ILogger _logger; +public class IndexModel : PageModel +{ + private readonly ILogger _logger; #if (GenerateApi) - private readonly IDownstreamWebApi _downstreamWebApi; + private readonly IDownstreamWebApi _downstreamWebApi; - public IndexModel(ILogger logger, - IDownstreamWebApi downstreamWebApi) - { - _logger = logger; - _downstreamWebApi = downstreamWebApi; - } + public IndexModel(ILogger logger, + IDownstreamWebApi downstreamWebApi) + { + _logger = logger; + _downstreamWebApi = downstreamWebApi; + } - public async Task OnGet() + public async Task OnGet() + { + using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) { - using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); - if (response.StatusCode == System.Net.HttpStatusCode.OK) - { - var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - ViewData["ApiResult"] = apiResult; - } - else - { - var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); - } + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + ViewData["ApiResult"] = apiResult; } -#elseif (GenerateGraph) - private readonly GraphServiceClient _graphServiceClient; - - public IndexModel(ILogger logger, - GraphServiceClient graphServiceClient) + else { - _logger = logger; - _graphServiceClient = graphServiceClient; + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } + } +#elseif (GenerateGraph) + private readonly GraphServiceClient _graphServiceClient; - public async Task OnGet() - { - var user = await _graphServiceClient.Me.Request().GetAsync(); + public IndexModel(ILogger logger, + GraphServiceClient graphServiceClient) + { + _logger = logger; + _graphServiceClient = graphServiceClient; + } - ViewData["ApiResult"] = user.DisplayName; - } + public async Task OnGet() + { + var user = await _graphServiceClient.Me.Request().GetAsync(); + + ViewData["ApiResult"] = user.DisplayName; + } #else - public IndexModel(ILogger logger) - { - _logger = logger; - } + public IndexModel(ILogger logger) + { + _logger = logger; + } - public void OnGet() - { + public void OnGet() + { - } -#endif } +#endif } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Privacy.cshtml.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Privacy.cshtml.cs index 5fa47ed6751d..83f879b16b81 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Privacy.cshtml.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/RazorPagesWeb-CSharp/Pages/Privacy.cshtml.cs @@ -1,19 +1,19 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -namespace Company.WebApplication1.Pages +namespace Company.WebApplication1.Pages; + +public class PrivacyModel : PageModel { - public class PrivacyModel : PageModel - { - private readonly ILogger _logger; + private readonly ILogger _logger; - public PrivacyModel(ILogger logger) - { - _logger = logger; - } + public PrivacyModel(ILogger logger) + { + _logger = logger; + } - public void OnGet() - { - } + public void OnGet() + { } } + diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Controllers/HomeController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Controllers/HomeController.cs index 25632ef42779..93e8d95a2afb 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Controllers/HomeController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Controllers/HomeController.cs @@ -14,83 +14,82 @@ #endif using Company.WebApplication1.Models; -namespace Company.WebApplication1.Controllers -{ +namespace Company.WebApplication1.Controllers; + #if (OrganizationalAuth) - [Authorize] +[Authorize] #endif - public class HomeController : Controller - { - private readonly ILogger _logger; +public class HomeController : Controller +{ + private readonly ILogger _logger; #if (GenerateApi) - private readonly IDownstreamWebApi _downstreamWebApi; + private readonly IDownstreamWebApi _downstreamWebApi; - public HomeController(ILogger logger, - IDownstreamWebApi downstreamWebApi) - { - _logger = logger; - _downstreamWebApi = downstreamWebApi; - } + public HomeController(ILogger logger, + IDownstreamWebApi downstreamWebApi) + { + _logger = logger; + _downstreamWebApi = downstreamWebApi; + } - [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")] - public async Task Index() + [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")] + public async Task Index() + { + using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) { - using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); - if (response.StatusCode == System.Net.HttpStatusCode.OK) - { - var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - ViewData["ApiResult"] = apiResult; - } - else - { - var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); - } - return View(); + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + ViewData["ApiResult"] = apiResult; } + else + { + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); + } + return View(); + } #elseif (GenerateGraph) - private readonly GraphServiceClient _graphServiceClient; + private readonly GraphServiceClient _graphServiceClient; - public HomeController(ILogger logger, - GraphServiceClient graphServiceClient) - { - _logger = logger; - _graphServiceClient = graphServiceClient; - } + public HomeController(ILogger logger, + GraphServiceClient graphServiceClient) + { + _logger = logger; + _graphServiceClient = graphServiceClient; + } - [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")] - public async Task Index() - { - var user = await _graphServiceClient.Me.Request().GetAsync(); - ViewData["ApiResult"] = user.DisplayName; + [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")] + public async Task Index() + { + var user = await _graphServiceClient.Me.Request().GetAsync(); + ViewData["ApiResult"] = user.DisplayName; - return View(); - } + return View(); + } #else - public HomeController(ILogger logger) - { - _logger = logger; - } + public HomeController(ILogger logger) + { + _logger = logger; + } - public IActionResult Index() - { - return View(); - } + public IActionResult Index() + { + return View(); + } #endif - public IActionResult Privacy() - { - return View(); - } + public IActionResult Privacy() + { + return View(); + } #if (OrganizationalAuth) - [AllowAnonymous] + [AllowAnonymous] #endif - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - public IActionResult Error() - { - return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); - } + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] + public IActionResult Error() + { + return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Data/ApplicationDbContext.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Data/ApplicationDbContext.cs index d883b6ecc1f8..4e8fb8cbf43a 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Data/ApplicationDbContext.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Data/ApplicationDbContext.cs @@ -1,13 +1,12 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; -namespace Company.WebApplication1.Data +namespace Company.WebApplication1.Data; + +public class ApplicationDbContext : IdentityDbContext { - public class ApplicationDbContext : IdentityDbContext + public ApplicationDbContext(DbContextOptions options) + : base(options) { - public ApplicationDbContext(DbContextOptions options) - : base(options) - { - } } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Models/ErrorViewModel.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Models/ErrorViewModel.cs index bfa680309b18..37f022d24701 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Models/ErrorViewModel.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Models/ErrorViewModel.cs @@ -1,9 +1,8 @@ -namespace Company.WebApplication1.Models +namespace Company.WebApplication1.Models; + +public class ErrorViewModel { - public class ErrorViewModel - { - public string? RequestId { get; set; } + public string? RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - } + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs index 8546a92a571e..019341717912 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/Controllers/WeatherForecastController.cs @@ -15,108 +15,107 @@ using Microsoft.Graph; #endif -namespace Company.WebApplication1.Controllers -{ +namespace Company.WebApplication1.Controllers; + #if (!NoAuth) - [Authorize] +[Authorize] #endif - [ApiController] - [Route("[controller]")] - public class WeatherForecastController : ControllerBase +[ApiController] +[Route("[controller]")] +public class WeatherForecastController : ControllerBase +{ + private static readonly string[] Summaries = new[] { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; - private readonly ILogger _logger; + private readonly ILogger _logger; #if (OrganizationalAuth || IndividualB2CAuth) - // The Web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API - static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; + // The Web API will only accept tokens 1) for users, and 2) having the "api-scope" scope for this API + static readonly string[] scopeRequiredByApi = new string[] { "api-scope" }; #endif #if (GenerateApi) - private readonly IDownstreamWebApi _downstreamWebApi; + private readonly IDownstreamWebApi _downstreamWebApi; + + public WeatherForecastController(ILogger logger, + IDownstreamWebApi downstreamWebApi) + { + _logger = logger; + _downstreamWebApi = downstreamWebApi; + } + + [HttpGet] + public async Task> Get() + { + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); - public WeatherForecastController(ILogger logger, - IDownstreamWebApi downstreamWebApi) + using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.OK) { - _logger = logger; - _downstreamWebApi = downstreamWebApi; + var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + // Do something } - - [HttpGet] - public async Task> Get() + else { - 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}"); - } - - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); + var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}"); } -#elseif (GenerateGraph) - private readonly GraphServiceClient _graphServiceClient; - - public WeatherForecastController(ILogger logger, - GraphServiceClient graphServiceClient) + return Enumerable.Range(1, 5).Select(index => new WeatherForecast { - _logger = logger; - _graphServiceClient = graphServiceClient; - } + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } - [HttpGet] - public async Task> Get() - { - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); - var user = await _graphServiceClient.Me.Request().GetAsync(); +#elseif (GenerateGraph) + private readonly GraphServiceClient _graphServiceClient; - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } -#else - public WeatherForecastController(ILogger logger) - { + public WeatherForecastController(ILogger logger, + GraphServiceClient graphServiceClient) + { _logger = logger; - } + _graphServiceClient = graphServiceClient; + } + + [HttpGet] + public async Task> Get() + { + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); + var user = await _graphServiceClient.Me.Request().GetAsync(); - [HttpGet] - public IEnumerable Get() + return Enumerable.Range(1, 5).Select(index => new WeatherForecast { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } +#else + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet] + public IEnumerable Get() + { #if (OrganizationalAuth || IndividualB2CAuth) - HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); + HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi); #endif - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }) - .ToArray(); - } -#endif + return Enumerable.Range(1, 5).Select(index => new WeatherForecast + { + Date = DateTime.Now.AddDays(index), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); } +#endif } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/WeatherForecast.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/WeatherForecast.cs index 147bef00be26..79d043e07429 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/WeatherForecast.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/WebApi-CSharp/WeatherForecast.cs @@ -1,13 +1,12 @@ -namespace Company.WebApplication1 +namespace Company.WebApplication1; + +public class WeatherForecast { - public class WeatherForecast - { - public DateTime Date { get; set; } + public DateTime Date { get; set; } - public int TemperatureC { get; set; } + public int TemperatureC { get; set; } - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - public string? Summary { get; set; } - } + public string? Summary { get; set; } } diff --git a/src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs b/src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs index a0c03d969faf..14b4443e25cf 100644 --- a/src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs +++ b/src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs @@ -1,27 +1,26 @@ -namespace Company.Application1 +namespace Company.Application1; + +public class Worker : BackgroundService { - public class Worker : BackgroundService - { - private readonly ILogger _logger; + private readonly ILogger _logger; - public Worker(ILogger logger) - { - _logger = logger; - } + public Worker(ILogger logger) + { + _logger = logger; + } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) { - while (!stoppingToken.IsCancellationRequested) + _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); + try + { + await Task.Delay(1000, stoppingToken); + } + catch (OperationCanceledException) { - _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); - try - { - await Task.Delay(1000, stoppingToken); - } - catch (OperationCanceledException) - { - return; - } + return; } } }