コード例 #1
0
ファイル: Startup.cs プロジェクト: xluckywang/PoJun.Shadow
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="httpContextAccessor"></param>
        public async void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            MyHttpContext.HttpContextAccessor = httpContextAccessor;

            #region 解决跨域

            //解决跨域(如果不用可以注释掉)
            app.UseCors("EnableCrossDomain");

            #endregion

            app.UseCors();
            app.UseStaticFiles();//注册wwwroot静态文件(如果不用可以注释掉)
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            #region 启动Job

            //执行数据导入定时同步Job
            var quartz = app.ApplicationServices.GetRequiredService <QuartzStartup>();
            //【每分钟执行一次】
            await quartz.Start <TestJob>("SyncTask", nameof(TestJob), "0 0/1 * * * ? ");

            #endregion

            #region 启用Swagger

            //启用Swagger中间件
            app.UseSwagger();
            //配置SwaggerUI
            app.UseSwaggerUI(c =>
            {
                foreach (var item in Provider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"/swagger/{item.GroupName}/swagger.json", SysUtil.GetSystemId() + item.ApiVersion);
                }
            });

            #endregion
        }
コード例 #2
0
        /// <summary>
        /// 进入处理
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            #region 获取传入的数据

            var jsonData = string.Empty;

            if (context.HttpContext.Request.ContentType != null)
            {
                var contentType = context.HttpContext.Request.ContentType.ToLower();
                if ((contentType.Contains("application/x-www-form-urlencoded") ||
                     contentType.Contains("multipart/form-data")) &&
                    context.HttpContext.Request.ContentLength != null &&
                    context.HttpContext.Request.ContentLength > 0)
                {
                    jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(context.HttpContext.Request.Form);
                }
                else if (contentType.Contains("application/json"))
                {
                    foreach (var item in context.ActionArguments)
                    {
                        jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(item.Value);
                        continue;
                    }
                }
            }

            #endregion

            #region 新增接口日志

            //获取日志ID
            var logTraceID  = PoJun.Util.Helpers.Id.GetGuidBy32();
            var requestTime = DateTime.Now;

            var logParam = new AddRequestLogParam();
            logParam.APIName = context.HttpContext.Request.Path;
            //这里存储的是客户端的IP+端口
            logParam.ClientHost  = $"{context.HttpContext.Connection.RemoteIpAddress.ToString()}:{context.HttpContext.Connection.RemotePort}";
            logParam.Headers     = Newtonsoft.Json.JsonConvert.SerializeObject(context.HttpContext.Request.Headers.ToList());
            logParam.Level       = 1;
            logParam.RequestBody = jsonData;
            //这里存储的当前服务器的IP+端口+接口地址+url参数
            logParam.ServerHost  = $"{SysUtil.Ip}:{context.HttpContext.Request.Host.Port}{context.HttpContext.Request.Path}{context.HttpContext.Request.QueryString}";
            logParam.SystemID    = SysUtil.GetSystemId();
            logParam.TraceID     = logTraceID;
            logParam.RequestTime = requestTime;

            //新增日志
            var log = await apiLogService.AddRequestLogAsync(logParam);

            #endregion

            #region 向后传输数据

            //把日志ID写入
            context.HttpContext.Items.Add(nameof(APILogConfig.PoJun_LogTraceID), logTraceID);
            context.HttpContext.Request.Headers.Add(nameof(APILogConfig.PoJun_LogTraceID), logTraceID);
            //把接口请求时间写入
            context.HttpContext.Items.Add(nameof(APILogConfig.RequestTime), requestTime);
            context.HttpContext.Request.Headers.Add(nameof(APILogConfig.RequestTime), requestTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            #endregion

            #region 全局DTO对象参数验证

            if (!context.ModelState.IsValid)
            {
                //使用自定义参数绑定验证体系
                var    modelState = context.ModelState.FirstOrDefault(f => f.Value.Errors.Any());
                string errorMsg   = modelState.Value.Errors.First().ErrorMessage;
                throw new ParamErrorException(errorMsg);
            }

            #endregion

            await base.OnActionExecutionAsync(context, next);
        }
コード例 #3
0
        /// <summary>
        /// Post请求[异步]
        /// </summary>
        /// <param name="host">域名</param>
        /// <param name="apiName">接口名称(接口地址)</param>
        /// <param name="dicParameters">接口参数</param>
        /// <param name="headers">请求头</param>
        /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
        /// <param name="contentType">请求类型</param>
        /// <param name="isMultilevelNestingJson">是否为多层嵌套json</param>
        /// <returns></returns>
        public async Task <string> HttpPostAsync(string host, string apiName, IDictionary <string, string> dicParameters, Dictionary <string, string> headers = null, int timeout = 100, HttpContentType contentType = HttpContentType.Json, bool isMultilevelNestingJson = false)
        {
            var client = clientFactory.CreateClient("base");
            {
                #region Http基础设置

                //设置接口超时时间
                if (timeout > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, timeout);
                }

                HttpContent content      = new FormUrlEncodedContent(dicParameters);
                var         _contentType = (contentType == HttpContentType.Json ? "application/json" : "application/x-www-form-urlencoded");
                if (contentType == HttpContentType.Json)
                {
                    if (isMultilevelNestingJson)
                    {
                        content = new StringContent(dicParameters["json"]);
                    }
                    else
                    {
                        content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters));
                    }
                }
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_contentType);
                //设置HTTP请求头
                if (headers != null)
                {
                    foreach (KeyValuePair <string, string> header in headers)
                    {
                        content.Headers.Add(header.Key, header.Value);
                    }
                }

                #endregion

                #region 新增请求日志

                var log_request_param = new AddRequestLogParam();
                log_request_param.APIName       = apiName.ToString().ToLower();
                log_request_param.ClientHost    = SysUtil.Ip;
                log_request_param.RequestTime   = DateTime.Now;
                log_request_param.ServerHost    = host;
                log_request_param.SystemID      = SysUtil.GetSystemId();
                log_request_param.TraceID       = PoJun.Util.Helpers.Id.GetGuidBy32();
                log_request_param.Level         = 2;
                log_request_param.ParentTraceID = SysUtil.GetTraceId();
                log_request_param.RequestBody   = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters);
                if (SysUtil.GetTraceId() != null)
                {
                    log_request_param.Level         = 2;
                    log_request_param.ParentTraceID = SysUtil.GetTraceId();
                }
                else
                {
                    log_request_param.Level = 1;
                }
                var log_request_result = await apiLogService.AddRequestLogAsync(log_request_param);

                #endregion

                #region 发起Http请求

                var url = $"{host}{apiName}";
                //异步发送请求
                var events = await client.PostAsync(url, content);

                //异步获取请求的结果
                var strResult = await events.Content.ReadAsStringAsync();

                #endregion

                #region 新增响应日志

                var log_response_param = new AddResponseLogParam();
                log_response_param.IsError       = false;
                log_response_param.ParentTraceID = log_request_param.TraceID;
                log_response_param.ResponseBody  = strResult;
                log_response_param.ResponseTime  = DateTime.Now;
                log_response_param.TimeCost      = Convert.ToInt32((log_response_param.ResponseTime - log_request_param.RequestTime).TotalMilliseconds);

                await apiLogService.AddResponseLogAsync(log_response_param);

                #endregion

                #region 返回结果

                return(strResult);

                #endregion
            }
        }
コード例 #4
0
        /// <summary>
        /// GET请求[同步]
        /// </summary>
        /// <typeparam name="T">只能传入DTO对象</typeparam>
        /// <param name="host">域名</param>
        /// <param name="apiName">接口名称(接口地址)</param>
        /// <param name="headers">请求头</param>
        /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
        /// <returns></returns>
        public T HttpGet <T>(string host, string apiName, Dictionary <string, string> headers = null, int timeout = 100)
        {
            var client = clientFactory.CreateClient("base");
            {
                #region Http基础设置

                //设置HTTP请求头
                if (headers != null)
                {
                    foreach (KeyValuePair <string, string> header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }
                //设置接口超时时间
                if (timeout > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, timeout);
                }

                #endregion

                #region 新增请求日志

                var log_request_param = new AddRequestLogParam();
                log_request_param.APIName       = apiName.ToString().ToLower();
                log_request_param.ClientHost    = SysUtil.Ip;
                log_request_param.RequestTime   = DateTime.Now;
                log_request_param.ServerHost    = host;
                log_request_param.SystemID      = SysUtil.GetSystemId();
                log_request_param.TraceID       = PoJun.Util.Helpers.Id.GetGuidBy32();
                log_request_param.Level         = 2;
                log_request_param.ParentTraceID = SysUtil.GetTraceId();
                log_request_param.RequestBody   = null;
                if (SysUtil.GetTraceId() != null)
                {
                    log_request_param.Level         = 2;
                    log_request_param.ParentTraceID = SysUtil.GetTraceId();
                }
                else
                {
                    log_request_param.Level = 1;
                }
                var log_request_result = apiLogService.AddRequestLogAsync(log_request_param).Result;

                #endregion

                #region 发起Http请求

                var    url         = $"{host}{apiName}";
                Byte[] resultBytes = client.GetByteArrayAsync(url).Result;
                var    result      = Encoding.UTF8.GetString(resultBytes);

                #endregion

                #region 新增响应日志

                var log_response_param = new AddResponseLogParam();
                log_response_param.IsError       = false;
                log_response_param.ParentTraceID = log_request_param.TraceID;
                log_response_param.ResponseBody  = result;
                log_response_param.ResponseTime  = DateTime.Now;
                log_response_param.TimeCost      = Convert.ToInt32((log_response_param.ResponseTime - log_request_param.RequestTime).TotalMilliseconds);

                apiLogService.AddResponseLogAsync(log_response_param).Wait();

                #endregion

                #region 返回结果

                return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(result));

                #endregion
            }
        }
コード例 #5
0
        /// <summary>
        /// Post请求[同步]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="host">域名</param>
        /// <param name="apiName">接口名称(接口地址)</param>
        /// <param name="dicParameters">接口参数</param>
        /// <param name="httpHandler">httpHandler</param>
        /// <param name="headers">请求头</param>
        /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
        /// <param name="contentType">请求类型</param>
        /// <returns></returns>
        public T HttpPost <T>(string host, string apiName, IDictionary <string, string> dicParameters, DiscoveryHttpClientHandler httpHandler = null, Dictionary <string, string> headers = null, int timeout = 100, HttpContentType contentType = HttpContentType.Json)
        {
            using (HttpClient client = ((httpHandler == null) ? new HttpClient() : new HttpClient(httpHandler)))
            {
                #region Http基础设置

                //设置接口超时时间
                if (timeout > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, timeout);
                }

                HttpContent content      = new FormUrlEncodedContent(dicParameters);
                var         _contentType = (contentType == HttpContentType.Json ? "application/json" : "application/x-www-form-urlencoded");
                if (contentType == HttpContentType.Json)
                {
                    content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters));
                }
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(_contentType);
                //设置HTTP请求头
                if (headers != null)
                {
                    foreach (KeyValuePair <string, string> header in headers)
                    {
                        content.Headers.Add(header.Key, header.Value);
                    }
                }

                #endregion

                #region 新增请求日志

                var log_request_param = new AddRequestLogParam();
                log_request_param.APIName     = apiName;
                log_request_param.ClientHost  = PoJun.Util.Helpers.Web.Host;
                log_request_param.RequestTime = DateTime.Now;
                log_request_param.ServerHost  = host;
                log_request_param.SystemID    = SysUtil.GetSystemId();
                log_request_param.TraceID     = PoJun.Util.Helpers.Id.GetGuidBy32();
                log_request_param.RequestBody = Newtonsoft.Json.JsonConvert.SerializeObject(dicParameters);
                if (SysUtil.GetTraceId() != null)
                {
                    log_request_param.Level         = 2;
                    log_request_param.ParentTraceID = SysUtil.GetTraceId();
                }
                else
                {
                    log_request_param.Level = 1;
                }
                var log_request_result = apiLogService.AddRequestLogAsync(log_request_param).Result;

                #endregion

                #region 发起Http请求

                var url = $"{host}{apiName}";
                //异步发送请求
                var events = client.PostAsync(url, content).Result;
                //异步获取请求的结果
                var strResult = events.Content.ReadAsStringAsync().Result;

                #endregion

                #region 新增响应日志

                var log_response_param = new AddResponseLogParam();
                log_response_param.IsError       = false;
                log_response_param.ParentTraceID = log_request_param.TraceID;
                log_response_param.ResponseBody  = strResult;
                log_response_param.ResponseTime  = DateTime.Now;
                log_response_param.TimeCost      = Convert.ToInt32((log_response_param.ResponseTime - log_request_param.RequestTime).TotalMilliseconds);

                apiLogService.AddResponseLogAsync(log_response_param).Wait();

                #endregion

                #region 返回结果

                return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(strResult));

                #endregion
            }
        }
コード例 #6
0
        /// <summary>
        /// GET请求[异步]
        /// </summary>
        /// <param name="host">域名</param>
        /// <param name="apiName">接口名称(接口地址)</param>
        /// <param name="headers">请求头</param>
        /// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
        /// <returns></returns>
        public async Task <string> HttpGetAsync(string host, string apiName, Dictionary <string, string> headers = null, int timeout = 0)
        {
            using (HttpClient client = new HttpClient())
            {
                #region Http基础设置

                //设置HTTP请求头
                if (headers != null)
                {
                    foreach (KeyValuePair <string, string> header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }
                //设置接口超时时间
                if (timeout > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, timeout);
                }

                #endregion

                #region 新增请求日志

                var log_request_param = new AddRequestLogParam();
                log_request_param.APIName     = apiName;
                log_request_param.ClientHost  = PoJun.Util.Helpers.Web.Host;
                log_request_param.RequestTime = DateTime.Now;
                log_request_param.ServerHost  = host;
                log_request_param.SystemID    = SysUtil.GetSystemId();
                log_request_param.TraceID     = PoJun.Util.Helpers.Id.GetGuidBy32();
                log_request_param.RequestBody = null;
                if (SysUtil.GetTraceId() != null)
                {
                    log_request_param.Level         = 2;
                    log_request_param.ParentTraceID = SysUtil.GetTraceId();
                }
                else
                {
                    log_request_param.Level = 1;
                }
                var log_request_result = await apiLogService.AddRequestLogAsync(log_request_param);

                #endregion

                #region 发起Http请求

                var    url         = $"{host}{apiName}";
                Byte[] resultBytes = await client.GetByteArrayAsync(url);

                var result = Encoding.UTF8.GetString(resultBytes);

                #endregion

                #region 新增响应日志

                var log_response_param = new AddResponseLogParam();
                log_response_param.IsError       = false;
                log_response_param.ParentTraceID = log_request_param.TraceID;
                log_response_param.ResponseBody  = result;
                log_response_param.ResponseTime  = DateTime.Now;
                log_response_param.TimeCost      = Convert.ToInt32((log_response_param.ResponseTime - log_request_param.RequestTime).TotalMilliseconds);

                await apiLogService.AddResponseLogAsync(log_response_param);

                #endregion

                #region 返回结果

                return(result);

                #endregion
            }
        }