Beispiel #1
0
 protected virtual void AddMediatR(IServiceCollection services)
 {
     if (AssembliesMidiatR.Any())
     {
         services.AddMediatR(AssembliesMidiatR.Select(p => AppDomain.CurrentDomain.Load(p)).ToArray());
     }
     else
     {
         ImprovedLogger.Write("Please, inform the 'AssembliesMidiatR' inside contructor Startup class!");
     }
 }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public virtual void ConfigureServices(IServiceCollection services)
        {
            if (AuthenticationEnabled && Configuration.GetSection("TokenConfiguration") != null)
            {
                services.AddOptions();
                services.Configure <TokenConfiguration>(options => Configuration.GetSection("TokenConfiguration").Bind(options));
                services.AddSingleton <SigningConfigurations, SigningConfigurations>();

                AddAuthentication(services);
                AddAuthorization(services);
            }
            else
            {
                ImprovedLogger.Write(@"if you wish use token/authentication, please add 'TokenConfiguration' Section in your appsettings.json with properties as follows:
                                      'SecretKey', 'Audience', 'Issuer', 'Seconds'");
            }

            services.AddSingleton <IImprovedUnitOfWork, ImprovedUnitOfWork>()
            .AddSingleton(Configuration);


            AddMediatR(services);
            AddAutoMapper(services);

            if (SwaggerEnabled)
            {
                AddSwagger(services);
            }

            if (AuthenticationEnabled && Configuration.GetSection("TokenConfiguration") != null)
            {
                _mvcBuilder = services.AddMvc(config =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                                 .RequireAuthenticatedUser().Build();

                    config.Filters.Add(new AuthorizeFilter(policy));
                });
            }
            else
            {
                _mvcBuilder = services.AddMvc();
            }

            MvcJsonOptions(_mvcBuilder);
        }
Beispiel #3
0
        protected virtual void AddSwagger(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                try
                {
                    c.SwaggerDoc("v1", new Info
                    {
                        Version        = "v1",
                        Title          = "Improved Api",
                        Description    = "An Example how to improve your api",
                        TermsOfService = "None",
                        Contact        = new Contact()
                        {
                            Name = "Improved API", Url = "https://github.com/marcoslcosta/ImprovedApi"
                        }
                    });
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    c.IncludeXmlComments(xmlPath);
                    c.CustomSchemaIds(x => x.FullName);
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

                    if (AuthenticationEnabled)
                    {
                        c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                            In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                        });
                        c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                            { "Bearer", Enumerable.Empty <string>() },
                        });
                    }
                }
                catch (Exception ex)
                {
                    ImprovedLogger.Write($@"Please add {Path.Combine(AppContext.BaseDirectory, Assembly.GetExecutingAssembly().GetName().Name)}.xml in your project. \n
                        Go to properties -> build -> select checkbox 'XML documentation file' ");
                }
            });
        }
        private static Task HandleExceptionAsync(HttpContext context, Exception exception, IImprovedUnitOfWork unitOfWork)
        {
            var code   = HttpStatusCode.InternalServerError; // 500 if unexpected
            var result = string.Empty;

            if (exception is EntityException)
            {
                code   = HttpStatusCode.BadRequest;
                result = JsonConvert.SerializeObject(new ResponseResult(null, (exception as EntityException).Notifications), new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
            }
            else if (exception is UnauthorizedException)
            {
                code   = HttpStatusCode.Unauthorized;
                result = JsonConvert.SerializeObject(new ResponseResult(null, (exception as UnauthorizedException).Notifications), new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
            }
            else
            {
                result = JsonConvert.SerializeObject(new { error = exception.Message }, new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });

#if DEBUG
                ImprovedLogger.Write(exception);
#endif
            }

            unitOfWork.Rollback();

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(result));
        }