VSCodeによるASP.NET Core サンプル(雑メモ)

### プロジェクト「WebApi」(ASP.NET Core)

#### Program.cs
```
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using HelloWorldApi.Middleware;

var builder = WebApplication.CreateBuilder(args);

// デフォルトで環境に基づいた設定を使用
var environment = builder.Environment.EnvironmentName; 

builder.Configuration
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true);

// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

// Add services to the container
builder.Services.AddControllers();

// Register Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

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

// Register the custom middleware
app.UseMiddleware<LoggingMiddleware>();

app.UseHttpsRedirection();
app.UseAuthorization();

app.MapControllers();

app.Run();
```


#### Controllers/TestController.cs
```
using Microsoft.AspNetCore.Mvc;

namespace HelloWorldApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        private readonly ILogger<TestController> _logger;

        public TestController(ILogger<TestController> logger)
        {
            _logger = logger;
        }

        [HttpGet("HelloWorld")]
        public IActionResult GetHelloWorld()
        {
            try
            {
                _logger.LogInformation("GET /api/Test/HelloWorld was called.");
                return Ok("Hello World");
            }
            catch(Exception e)
            {
                return this.StatusCode(500, e.Message);
            }
            finally
            {
                _logger.LogInformation("GET /api/Test/HelloWorld was done.");
            }
        }
    }
}
```


#### Middleware/LoggingMiddleware
```
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Threading.Tasks;

namespace HelloWorldApi.Middleware
{
    public class LoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<LoggingMiddleware> _logger;

        public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var stopwatch = Stopwatch.StartNew();
            
            // Log incoming request
            _logger.LogInformation("Handling request: {Method} {Url}", context.Request.Method, context.Request.Path);

            await _next(context);

            // Log outgoing response
            stopwatch.Stop();
            _logger.LogInformation("Finished handling request in {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
        }
    }
}
```



#### appsettings.json
```
{
  "AllowedHosts": "*"
}
```



#### appsettings.Development.json
```
{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://localhost:8080"
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  }
}
```



#### appsettings.Production.json
```
{
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://*:44380"
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  }
}
```