Exemple #1
0
        public virtual async Task <IActionResult> DeleteAsync(long id)
        {
            using (_logger.BeginScope($"{nameof(CoreApiController<TEntity, TViewModel, TApplicationService>)}.{nameof(CoreApiController<TEntity, TViewModel, TApplicationService>.DeleteAsync)}"))
            {
                var stopwatch = Stopwatch.StartNew();
                try
                {
                    var entity = await ApplicationService.DeleteAsync(id);

                    _logger.LogInformation("Id: {Id}, entity: {@Entity}", id, entity);

                    if (entity == null)
                    {
                        return(Ok(CoreResultModel.Create(HttpStatusCode.NotFound, data: entity)));
                    }

                    return(Ok(CoreResultModel.Create(HttpStatusCode.OK, data: entity)));
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Method failed.");
                    throw;
                }
                finally
                {
                    _logger.LogDebug("Method finished. Duration: {Duration}", stopwatch.Elapsed);
                }
            }
        }
Exemple #2
0
        public async Task InvokeAsync(HttpContext context)
        {
            Stream originalResponseBody = context.Response.Body;

            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    context.Response.Body = memoryStream;

                    await _next(context);

                    memoryStream.Position = 0;

                    if (context.Response.StatusCode != (int)HttpStatusCode.OK)
                    {
                        CoreResultModel coreResultModel = null;
                        switch (context.Response.StatusCode)
                        {
                        case (int)HttpStatusCode.Unauthorized:
                            coreResultModel = CoreResultModel.Create((HttpStatusCode)context.Response.StatusCode, "Not authorized user.");
                            break;

                        default:
                            coreResultModel = CoreResultModel.Create((HttpStatusCode)context.Response.StatusCode, "An error occurred during execution.");
                            break;
                        }

                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Body.SetLength(0);
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(JsonSerializer.Serialize(coreResultModel));
                    }

                    memoryStream.Position = 0;
                    await context.Response.Body.CopyToAsync(originalResponseBody);

                    context.Response.Body = originalResponseBody;
                }
            }
            finally
            {
                context.Response.Body = originalResponseBody;
            }
        }
Exemple #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddApplication();
            services.AddInfrastructure(Configuration);

            services.AddAuthentication("Client").AddScheme <ClientAuthenticationOptions, ClientAuthenticationHandler>("Client", null);

            services.AddControllers(options =>
            {
                options.Filters.Add <CoreAsyncExceptionFilter>();
                options.InputFormatters.Add(new ProductTextInputFormatter());
            });

            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
                o.UseApiBehavior    = false;
            });

            services.AddMvc().AddFluentValidation().ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = x =>
                {
                    var errors = string.Join(';', x.ModelState.Values.Where(y => y.Errors.Count > 0)
                                             .SelectMany(y => y.Errors)
                                             .Select(y => y.ErrorMessage));

                    return(new OkObjectResult(CoreResultModel.Create(HttpStatusCode.BadRequest, errors)));
                };
            });

            services.AddTransient <IFirstProductNameValidator, FirstProductNameValidator>();
            services.AddTransient <ISecondProductNameValidator, SecondProductNameValidator>();
            services.AddTransient <IFirstProductDescriptionValidator, FirstProductDescriptionValidator>();
            services.AddTransient <ISecondProductDescriptionValidator, SecondProductDescriptionValidator>();

            services.AddTransient <IValidator <ProductViewModel>, ProductViewModelValidator>();

            services.AddLogging(builder =>
            {
                builder.AddSerilog();
            });
        }
Exemple #4
0
        public virtual async Task <IActionResult> GetAsync()
        {
            using (_logger.BeginScope($"{nameof(CoreApiController<TEntity, TViewModel, TApplicationService>)}.{nameof(CoreApiController<TEntity, TViewModel, TApplicationService>.GetAsync)}"))
            {
                var stopwatch = Stopwatch.StartNew();
                try
                {
                    var entities = await ApplicationService.GetAsync();

                    return(Ok(CoreResultModel.Create(HttpStatusCode.OK, data: entities)));
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Method failed.");
                    throw;
                }
                finally
                {
                    _logger.LogDebug("Method finished. Duration: {Duration}", stopwatch.Elapsed);
                }
            }
        }
Exemple #5
0
        public virtual async Task <IActionResult> PostAsync(TViewModel viewModel)
        {
            using (_logger.BeginScope($"{nameof(CoreApiController<TEntity, TViewModel, TApplicationService>)}.{nameof(CoreApiController<TEntity, TViewModel, TApplicationService>.PostAsync)}"))
            {
                var stopwatch = Stopwatch.StartNew();
                try
                {
                    var entity = await ApplicationService.CreateAsync(viewModel);

                    _logger.LogInformation("View model: {@ViewModel}, entity: {@Entity}", viewModel, entity);
                    return(Ok(CoreResultModel.Create(HttpStatusCode.Created, data: entity)));
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Method failed.");
                    throw;
                }
                finally
                {
                    _logger.LogDebug("Method finished. Duration: {Duration}", stopwatch.Elapsed);
                }
            }
        }
 public async Task OnExceptionAsync(ExceptionContext context)
 {
     var coreModelResult = CoreResultModel.Create(HttpStatusCode.OK, context.Exception.Message);
     await context.HttpContext.Response.WriteAsync(JsonSerializer.Serialize(coreModelResult));
 }