Пример #1
0
        public static IServiceCollection AddKRFController(this IServiceCollection services, Action <MvcOptions> options)
        {
            services.AddControllers(options)
            .AddJsonOptions(o => KRFJsonSerializerOptions.GetJsonSerializerOptions(o.JsonSerializerOptions));

            return(services);
        }
Пример #2
0
        public static IServiceCollection AddKRFController(this IServiceCollection services)
        {
            services.AddControllers(o =>
            {
                o.AllowEmptyInputInBodyModelBinding = true;
                o.RespectBrowserAcceptHeader        = true;
                o.ReturnHttpNotAcceptable           = false;
            })
            .AddJsonOptions(o => KRFJsonSerializerOptions.GetJsonSerializerOptions(o.JsonSerializerOptions));

            return(services);
        }
Пример #3
0
        public static IApplicationBuilder ApiConfigure(this IApplicationBuilder app, AppConfiguration configuration, ILoggerFactory loggerFactory, bool isDev = false)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(AppConfiguration));
            }

            app.UseLocalization(configuration.LocalizationConfiguration);

            app.KRFLogAndExceptionHandlerConfigure(
                loggerFactory,
                configuration,
                isDev);

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseStatusCodePages(async ctx =>
            {
                var serializerOpt = KRFJsonSerializerOptions.GetJsonSerializerOptions();

                switch (ctx.HttpContext.Response.StatusCode)
                {
                case (( int )HttpStatusCode.Unauthorized):
                    {
                        string message = "Selected token is invalid or user is not authenticated";
                        string code    = null;
                        if (ctx.HttpContext.Response.Headers.TryGetValue(KRFConstants.AuthenticateHeader, out var authHeader))
                        {
                            code = authHeader[0];
                            switch (code)
                            {
                            case KRFTokenErrors.TokenSignatureErrorCode:
                                {
                                    message = "Invalid token signature, please logout and login again";
                                    break;
                                }

                            case KRFTokenErrors.TokenExpiredErrorCode:
                                {
                                    message = "Your token has expired, request new token from auth server and send new request";
                                    break;
                                }

                            default:
                                {
                                    code = KRFTokenErrors.TokenDefaultErrorCode;
                                    break;
                                }
                            }
                        }

                        if (!isDev)
                        {
                            message = "User is not authenticated";
                        }

                        await ctx.HttpContext.Response.WriteAsJsonAsync(new ErrorOut(HttpStatusCode.Unauthorized, message, ResponseErrorType.Application, "Authentication", code), serializerOpt);
                        break;
                    }

                case (( int )HttpStatusCode.Forbidden):
                    {
                        await ctx.HttpContext.Response.WriteAsJsonAsync(new ErrorOut(HttpStatusCode.Forbidden, "User is not allowed to resource", ResponseErrorType.Application, "Authorization", KRFConstants.AuthorizationErrorCode), serializerOpt);
                        break;
                    }

                case (( int )HttpStatusCode.NotFound):
                    {
                        await ctx.HttpContext.Response.WriteAsJsonAsync(new ErrorOut(HttpStatusCode.NotFound, "Could not find desired resource", ResponseErrorType.Application, KRFConstants.DefaultErrorCode), serializerOpt);
                        break;
                    }

                default:
                    {
                        await ctx.HttpContext.Response.WriteAsJsonAsync(new ErrorOut(( HttpStatusCode )ctx.HttpContext.Response.StatusCode, "Unknown error occurred", ResponseErrorType.Unknown, KRFConstants.DefaultErrorCode), serializerOpt);
                        break;
                    }
                }
            });

            app.CorsConfigure(configuration.CorsConfiguration, isDev);

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            return(app);
        }
Пример #4
0
        public ServerConfigurationHandler(string path)
        {
            try
            {
                var configPath = Path.IsPathRooted(path) ? path : $"{Environment.CurrentDirectory}\\{path}";
                //Read all json configurations from path
                var configurations  = new Dictionary <string, ServerConfiguration>();
                var configFilePaths = Directory.GetFiles(configPath, "*.json");

                foreach (var filePath in configFilePaths)
                {
                    var file = File.ReadAllText(filePath);
                    var data = JsonSerializer.Deserialize <ServerConfiguration>(file, KRFJsonSerializerOptions.GetJsonSerializerOptions());
                    configurations.Add(data.ServerName.ToLowerInvariant(), data);
                }

                this.ServerConfigurations = configurations;
            }
            catch (Exception ex)
            {
                throw new Exception($"Could not load configuration files - {ex.Message}");
            }
        }
        private static IApplicationBuilder _KRFExceptionHandlerMiddlewareConfigure(this IApplicationBuilder app, ILoggerFactory loggerFactory, AppConfiguration configuration, bool isDev = false)
        {
            var _eventId = new EventId(KRFConstants.ApiEventId, KRFConstants.LogExceptionEvtName);

            app.UseExceptionHandler(b => b.Run(async c =>
            {
                var error = ( IExceptionHandlerFeature )c.Features[typeof(IExceptionHandlerFeature)];

                if (configuration.EnableReqLogs || isDev)
                {
                    var requestToken = c.Request.Headers[configuration.TokenIdentifier];
                    string reqBody;
                    if (c.Request.Body.CanSeek &&
                        !c.Request.Method.Equals(KRFConstants.GetMethod, StringComparison.InvariantCultureIgnoreCase) &&
                        !c.Request.Method.Equals(KRFConstants.DeleteMethod, StringComparison.InvariantCultureIgnoreCase) &&
                        c.Request.ContentLength != null && (!configuration.RequestBufferSize.HasValue || configuration.RequestBufferSize.Value >= c.Request.ContentLength) &&
                        c.Request.ContentType != null && c.Request.ContentType.Contains(KRFConstants.JsonContentType, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var body = new MemoryStream();
                        c.Request.Body.Seek(0, SeekOrigin.Begin);
                        await c.Request.Body.CopyToAsync(body);
                        c.Request.Body.Seek(0, SeekOrigin.Begin);
                        body.Seek(0, SeekOrigin.Begin);

                        using (var reqReader = new StreamReader(body))
                        {
                            reqBody = await reqReader.ReadToEndAsync();
                        }
                    }
                    else
                    {
                        reqBody = "Could not read request body: Get method or Request reading disabled or content too long";
                    }
                    var requestUrl = c.Request.Path + c.Request.QueryString;
                    var appLogger  = loggerFactory.CreateLogger(string.Format("{0} - {1}", configuration.ApiName, "Exceptions"));

                    var log = new StringBuilder();
                    log.Append("\n------------------------------------------------------");
                    log.Append("\n                     Request Log:");
                    log.Append("\n------------------------------------------------------");
                    log.Append("\nTimeStamp:");
                    log.Append(DateTime.Now.ToString(KRFConstants.TimeStampFormat));
                    log.Append("\nRequest: ");
                    log.Append(requestUrl);
                    log.Append("\nRequest Method: ");
                    log.Append(c.Request.Method);
                    log.Append("\nRequest Token: ");
                    log.Append(requestToken);
                    log.Append("\nStatusCode:");
                    log.Append(c.Response.StatusCode.ToString());
                    log.Append("\nRequest Body:\n");
                    log.Append(reqBody);
                    log.Append("\n\n------------------------------------------------------");
                    log.Append("\n                     Exception:");
                    log.Append("\n------------------------------------------------------\n");
                    log.Append(error.Error.Message);

                    appLogger.LogError(_eventId, error.Error, log.ToString());
                }

                //Check specific exceptons first
                var serializerOpt = KRFJsonSerializerOptions.GetJsonSerializerOptions();
                switch (error.Error)
                {
                case HttpRequestException httpEx:
                    {
                        await c.Response.WriteAsJsonAsync(new ErrorOut(( HttpStatusCode )c.Response.StatusCode, "Could not execute request to the server", ResponseErrorType.Exception, "HttpRequest", KRFConstants.HttpExErrorCode), serializerOpt);
                        break;
                    }

                case KRFMemoryCacheException memoryCacheException:
                    {
                        await c.Response.WriteAsJsonAsync(new ErrorOut(( HttpStatusCode )c.Response.StatusCode, memoryCacheException.Message, ResponseErrorType.Exception, "MemoryCache", memoryCacheException.Code), serializerOpt);
                        break;
                    }

                default:
                    {
                        await c.Response.WriteAsJsonAsync(new ErrorOut(( HttpStatusCode )c.Response.StatusCode, error.Error.Message, ResponseErrorType.Exception, "Exception", KRFConstants.DefaultErrorCode), serializerOpt);
                        break;
                    }
                }
            }));


            return(app);
        }
Пример #6
0
        private static async Task <KRFHttpResponse <TResp> > RequestHttpInternal <TResp>(KRFHttpRequest request, string stringBody = null)
            where TResp : class
        {
            HttpResponseMessage response = null;
            string route = string.Format("{0}{1}", request.Route, request.QueryString);

            try
            {
                using (var handler = new HttpClientHandler())
                {
                    if (request.ForceDisableSSL.HasValue && request.ForceDisableSSL.Value)
                    {
                        handler.ServerCertificateCustomValidationCallback = (message, cert, chain, err) =>
                        {
                            return(true);
                        };
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(request.CertificatePath))
                        {
                            //Add ssl certificate
                            if (!string.IsNullOrEmpty(request.CertificateKey))
                            {
                                //Add ssl certificate password
                            }
                        }
                    }

                    using (var client = new HttpClient(handler))
                    {
                        client.BaseAddress = new Uri(request.Url);
                        client.DefaultRequestHeaders.Accept.Append(new MediaTypeWithQualityHeaderValue(KRFConstants.JsonContentType));

                        if (!string.IsNullOrEmpty(request.BearerToken) && !string.IsNullOrEmpty(request.BearerTokenHeader))
                        {
                            client.DefaultRequestHeaders.Add(request.BearerTokenHeader, request.BearerToken);
                        }

                        if (request.Timeout.HasValue)
                        {
                            client.Timeout = new TimeSpan(0, 0, request.Timeout.Value);
                        }

                        switch (request.Method)
                        {
                        case HttpMethodEnum.GET:
                        {
                            response = await client.GetAsync(route);

                            break;
                        }

                        case HttpMethodEnum.DELETE:
                        {
                            response = await client.DeleteAsync(route);

                            break;
                        }

                        case HttpMethodEnum.POST:
                        case HttpMethodEnum.PUT:
                        {
                            using (HttpContent req = new StringContent(stringBody ?? string.Empty, Encoding.UTF8))
                            {
                                req.Headers.ContentType.MediaType = KRFConstants.JsonContentType;
                                req.Headers.ContentType.CharSet   = "utf-8";

                                if (request.Method.Equals(HttpMethodEnum.POST))
                                {
                                    response = await client.PostAsync(route, req);
                                }
                                else
                                {
                                    response = await client.PutAsync(route, req);
                                }
                            }
                            break;
                        }
                        }

                        if (response == null || response.Content == null)
                        {
                            throw new Exception("No response found from service");
                        }


                        var respBody = await response.Content.ReadAsStringAsync();

                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            return(new KRFHttpResponse <TResp>
                            {
                                Response = JsonSerializer.Deserialize <TResp>(respBody, KRFJsonSerializerOptions.GetJsonSerializerOptions()),
                                HttpStatus = response.StatusCode,
                                ResponseHeaders = response.Headers
                            });
                        }

                        return(new KRFHttpResponse <TResp>
                        {
                            Error = JsonSerializer.Deserialize <ErrorOut>(respBody, KRFJsonSerializerOptions.GetJsonSerializerOptions()),
                            HttpStatus = response.StatusCode,
                            ResponseHeaders = response.Headers
                        });
                    }
                }
            }
            catch
            {
                return(new KRFHttpResponse <TResp>
                {
                    Error = new ErrorOut(HttpStatusCode.InternalServerError, string.Format("Could not retrieve response from {0}/{1}", request.Url, route), ResponseErrorType.Proxy, KRFConstants.NotAvailableErrorCode),
                    HttpStatus = HttpStatusCode.InternalServerError
                });
            }
        }
Пример #7
0
        public static async Task <KRFHttpResponse <TResp> > RequestHttp <TBody, TResp>(KRFHttpRequestWithBody <TBody> request)
            where TBody : class
            where TResp : class
        {
            if (request == null)
            {
                throw new Exception("No request was defined for Http Rest call");
            }

            string stringBody = string.Empty;

            if (request.Body != null)
            {
                stringBody = request.Body is string?(request.Body as string) : JsonSerializer.Serialize(request.Body, KRFJsonSerializerOptions.GetJsonSerializerOptions());
            }

            return(await RequestHttpInternal <TResp>(request, stringBody));
        }