Created
November 15, 2023 20:14
-
-
Save log4code/eff4034f0c5c41ac1af12a6b5ad221e8 to your computer and use it in GitHub Desktop.
Slim Controller + MediatR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using MediatR; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Infrastructure; | |
using System.ComponentModel.DataAnnotations; | |
namespace SlimController.Controllers | |
{ | |
[ApiController] | |
[Route("[controller]")] | |
public class WeatherForecastController : ControllerBase | |
{ | |
private readonly ILogger<WeatherForecastController> _logger; | |
private readonly IMediator _mediator; | |
public WeatherForecastController(ILogger<WeatherForecastController> logger, IMediator mediator) | |
{ | |
_logger = logger; | |
_mediator = mediator; | |
} | |
[HttpGet(Name = "GetWeatherForecast")] | |
public async Task<IActionResult> Get([FromQuery] GetFutureWeatherRequest request) | |
{ | |
return (await _mediator.Send(request)).Result; | |
} | |
} | |
public class GetFutureWeatherRequest : IRequest<GetFutureWeatherResponse> | |
{ | |
[Range(1, 10)] | |
public int DaysToForecast { get; set; } | |
} | |
public class GetFutureWeatherResponse | |
{ | |
public GetFutureWeatherResponse(IActionResult result) | |
{ | |
_result = result; | |
} | |
private IActionResult _result; | |
public IActionResult Result | |
{ | |
get { return _result; } | |
} | |
public class GetFutureWeatherRequestHandler : IRequestHandler<GetFutureWeatherRequest, GetFutureWeatherResponse> | |
{ | |
private static readonly string[] Summaries = new[] | |
{ | |
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" | |
}; | |
public Task<GetFutureWeatherResponse> Handle(GetFutureWeatherRequest request, CancellationToken cancellationToken) | |
{ | |
var forecast = Enumerable.Range(1, request.DaysToForecast).Select(index => new WeatherForecast | |
{ | |
Date = DateTime.Now.AddDays(index), | |
TemperatureC = Random.Shared.Next(-20, 55), | |
Summary = Summaries[Random.Shared.Next(Summaries.Length)] | |
}) | |
.ToArray(); | |
var response = new GetFutureWeatherResponse(new OkObjectResult(forecast)); | |
return Task.FromResult(response); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment