Пример #1
0
        //This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // app.UseHsts();
            }

            //exception handling for 401 and 500
            app.UseExceptionHandler(appBuilder =>
            {
                appBuilder.Use(async(context, next) =>
                {
                    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;

                    //when authorization has failed, should retrun a json message to client
                    if (error != null && error.Error is SecurityTokenExpiredException)
                    {
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";

                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                        {
                            status  = 401,
                            message = "Its either token has expired or incorrect",
                            error   = "Forbidden route"
                        }));
                    }
                    //when orther error, retrun a error message json to client
                    else if (error != null && error.Error != null)
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                        {
                            status  = 500,
                            message = "Internal Server Error",
                            error   = error.Error.Message
                        }));
                    }
                    //when no error, do next.
                    else
                    {
                        await next();
                    }
                });
            });
            app.UseStaticFiles();
            //add swagger middleware and ui
            app.UseSwagger();
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "JK Api V1");
            });

            app.UseSecureHeadersMiddleware(ServiceExtensions.BuildDefaultConfiguration());

            app.UseAuthentication();

            //app.UseHttpsRedirection();

            app.UseMvc();

            app.UseCors();
        }