Skip to content

Instantly share code, notes, and snippets.

{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"WebApp.Api": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "api-docs",
"applicationUrl": "https://localhost:7224;http://localhost:5075",
"environmentVariables": {
app.UseReDoc(options =>
{
options.DocumentTitle = "ReDoc Sample Project";
options.SpecUrl = "/swagger/v1/swagger.json";
});
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
services.AddTransient(typeof(IRequestExceptionHandler<,,>), typeof(ExceptionHandlingBehavior<,,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<TRequest> logger;
public LoggingBehavior(ILogger<TRequest> logger)
{
this.logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
public class ExceptionHandlingBehavior<TRequest, TResponse, TException> : IRequestExceptionHandler<TRequest, TResponse, TException>
where TRequest : notnull
where TException : Exception
where TResponse : notnull, ServiceResponse
{
private readonly ILogger<ExceptionHandlingBehavior<TRequest, TResponse, TException>> logger;
public ExceptionHandlingBehavior(
ILogger<ExceptionHandlingBehavior<TRequest, TResponse, TException>> logger)
{
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
where TResponse : ServiceResponse, new()
{
private readonly IEnumerable<IValidator<TRequest>> validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
this.validators = validators;
[HttpGet("{id}")]
[ProducesResponseType(typeof(ServiceResponse), (int) HttpStatusCode.BadRequest)]
[ProducesResponseType(typeof(ServiceResponse), (int) HttpStatusCode.NotFound)]
[ProducesResponseType(typeof(ServiceResponse), (int) HttpStatusCode.OK)]
public async Task<IActionResult> Get(int id)
{
if (id <= 0)
{
return BadRequest(Messages.InvalidRequest);
}
public class GetSampleByIdQuery : IRequest<ServiceResponse>
{
public int Id { get; set; }
public GetSampleByIdQuery(int id)
{
Id = id;
}
}
public class GetSampleByIdHandler : IRequestHandler<GetSampleByIdQuery, ServiceResponse>
{
private readonly IReadOnlyRepository<Sample> repository;
public GetSampleByIdHandler(IReadOnlyRepository<Sample> repository)
{
this.repository = repository;
}
public async Task<ServiceDataResponse> Handle(GetSampleByIdQuery request, CancellationToken cancellationToken)
public interface ISampleService
{
ServiceDataResult GetAll();
ServiceDataResult Get(string id);
ServiceResult Add(AddSampleRequest request);
ServiceResult Update(UpdateSampleRequest request);
ServiceResult Delete(string id);
}
public class SampleService : ISampleService