Esempio n. 1
0
 public static void ConfigureExceptionHandler(this IApplicationBuilder app)
 {
     app.UseExceptionHandler(appError =>
                             appError.Run(async context =>
     {
         context.Response.ContentType = "application/json";
         var contextFeature           = context.Features.Get <IExceptionHandlerFeature>();
         if (contextFeature != null)
         {
             context.Response.StatusCode = contextFeature is ICustomException ?
                                           (int)HttpStatusCode.BadRequest :
                                           (int)HttpStatusCode.InternalServerError;
             var factory = new ErrorPayloadFactory(new string[] { contextFeature.Error.Message }, "Internal Server Error.");
             await context.Response.WriteAsync(factory.GetPayload().ToString)
             .ConfigureAwait(false);
         }
     }));
 }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Dependency Injection
            services.AddAutoMapper(typeof(GatewayProfile), typeof(DeviceProfile));
            services.AddDbContext <MusalaContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped <IGatewayService, GatewayService>();
            services.AddScoped <IDeviceService, DeviceService>();
            #endregion


            services.AddControllers();
            services.AddControllersWithViews()
            .AddNewtonsoftJson(options =>
                               options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            //services.AddDbContext<MusalaTestContext>(
            //    optionsAction =>
            //    optionsAction.UseMySql("server=10.8.130.250;port=3306;database=prueba;user=root;pwd=root", x => x.ServerVersion("8.0.19-mysql"))
            //    );
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errors = actionContext.ModelState
                                 .Where(e => e.Value.Errors.Count > 0)
                                 .Select(e => e.Value.Errors.First().ErrorMessage
                                         ).ToArray();

                    var factory = new ErrorPayloadFactory(error: errors, message: "Invalid input.");
                    return(new PayloadResult(factory.GetPayload(), HttpStatusCode.BadRequest));
                };
            });

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Title = "Api Docs", Version = "1.0"
                });
            }
                                   );
        }