Example #1
0
 private int getFilterTypeFromJson(string filterJson)
 {
     try
     {
         var dateTimeConverter = new IsoDateTimeConverter()
         {
             DateTimeFormat = FormattingConstant.NormalDateFormat
         };
         DeliveryItemFilterVM model = JsonConvert.DeserializeObject <DeliveryItemFilterVM>(filterJson, dateTimeConverter);
         return(model.FilterType);
     }
     catch
     {
         return(0);
     }
 }
Example #2
0
        public static string ToJson <T>(this T obj)
        {
            JsonSerializerSettings jsonSs = new JsonSerializerSettings();
            var timeConverter             = new IsoDateTimeConverter();

            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            jsonSs.Converters.Add(timeConverter);
            jsonSs.Converters.Add(new DataTableConverter());
            //jsonSs.Converters.Add(new JavaScriptDateTimeConverter());
            //jsonSs.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
            //jsonSs.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            //jsonSs.DateTimeZoneHandling = DateTimeZoneHandling.Local;
            string json = JsonConvert.SerializeObject(obj, Formatting.None, jsonSs);

            return(json);
        }
Example #3
0
        public static string ToJSON(this object oo)
        {
            Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();

            var iso = new IsoDateTimeConverter();

            iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";

            setting.Converters = new List <JsonConverter> {
                new StringEnumConverter(), iso
            };
            setting.Formatting            = Formatting.Indented;
            setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            // setting.en
            return(JsonConvert.SerializeObject(oo, setting));
        }
Example #4
0
        public void SerializeDateTime()
        {
            IsoDateTimeConverter converter = new IsoDateTimeConverter();

            DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc);
            string   result;

            result = JsonConvert.SerializeObject(d, converter);
            Assert.AreEqual(@"""2000-12-15T22:11:03.055Z""", result);

            Assert.AreEqual(d, JsonConvert.DeserializeObject <DateTime>(result, converter));

            d      = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Local);
            result = JsonConvert.SerializeObject(d, converter);
            Assert.AreEqual(@"""2000-12-15T22:11:03.055" + GetUtcOffsetText(d) + @"""", result);
        }
Example #5
0
    public static string RegExec(string nameText, string emCodeText, string mobileText, string passwordText)
    {
        IsoDateTimeConverter iso = new IsoDateTimeConverter();//序列化JSON对象时,日期的处理格式

        iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        string tempsql = @"select b.*,a.createbyid,a.createbyName,a.createDate,a.prtype,a.prreason,a.applydept,a.deptname  
                    from PUR_PR_Main_Form a 
                        inner join PUR_PR_Dtl_Form b on a.prno=b.prno 
                     where b.id=''";


        DataTable dt   = DbHelperSQL.Query(tempsql).Tables[0];
        var       json = JsonConvert.SerializeObject(dt, iso);

        return(json);
    }
Example #6
0
        public static string ToJson(object entity, string dateTimeFormat)
        {
            IsoDateTimeConverter converter = new IsoDateTimeConverter();

            converter.DateTimeStyles = DateTimeStyles.AssumeLocal;

            if (!string.IsNullOrEmpty(dateTimeFormat))
            {
                converter.DateTimeFormat = dateTimeFormat;
            }

            string jsonResult = JsonConvert.SerializeObject(entity,
                                                            converter);

            return(jsonResult);
        }
Example #7
0
        public void SerializeCustomFormattedDateTime()
        {
            IsoDateTimeConverter converter = new IsoDateTimeConverter
            {
                DateTimeFormat = "dd/MM/yyyy",
                Culture        = CultureInfo.InvariantCulture
            };

            string json = @"""09/12/2006""";

            DateTime d = JsonConvert.DeserializeObject <DateTime>(json, converter);

            Assert.AreEqual(9, d.Day);
            Assert.AreEqual(12, d.Month);
            Assert.AreEqual(2006, d.Year);
        }
Example #8
0
        /// <summary>
        ///     将object对象序列化成json字符串
        ///     转换成序列化对象
        ///     时间格式统一转化为 yyyy-MM-dd HH:mm:ss  不在使用 JsonConvert 默认的类型
        /// </summary>
        /// <typeparam name="obj"></typeparam>
        /// <param name="obj"></param>
        public static string ToJson(this object obj)
        {
            try {
                var timeFormat = new IsoDateTimeConverter {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                };
                if (obj == null)
                {
                    obj = string.Empty;
                }

                return(JsonConvert.SerializeObject(obj, Formatting.Indented, timeFormat));
            } catch {
                return(JsonConvert.SerializeObject(obj));
            }
        }
Example #9
0
        /// <summary>
        /// 将对象转成json
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string Encode(object o)
        {
            if (o == null || o.ToString() == "null")
            {
                return(null);
            }

            if (o != null && (o.GetType() == typeof(String) || o.GetType() == typeof(string)))
            {
                return(o.ToString());
            }
            IsoDateTimeConverter dt = new IsoDateTimeConverter();

            dt.DateTimeFormat = DateTimeFormat;
            return(JsonConvert.SerializeObject(o, dt));
        }
Example #10
0
        /// <summary>
        /// 请求数据列表
        /// </summary>
        /// <param name="companyId">所属单位ID</param>
        /// <param name="deptId">所属部门ID</param>
        /// <param name="question">查询关键字</param>
        /// <param name="starttime">开始日期</param>
        /// <param name="endtime">截止日期</param>
        /// <param name="rowStatus"></param>
        /// <param name="rows"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public string GetQuestionList(string companyId, string deptId, string question, string starttime, string endtime, int rowStatus, int rows, int page)
        {
            //var user = CurrentUser.CrmUser;

            var userId = "";

            var data = _crmDailyOneProblemRecordBll.GetSearchResult(companyId, deptId, userId, question, page, rows, starttime, endtime);

            //return CommonMethod.PageToJson(data);

            var timeConverter = new IsoDateTimeConverter {
                DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
            };

            return(JsonConvert.SerializeObject(data, timeConverter));
        }
        public static string SerializeObject(object obj)
        {
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter {
                DateTimeFormat = "yyyy-MM-dd HH:mm"
            };

            return(JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings
            {
                //设置转换时间类型
                Converters = new List <JsonConverter> {
                    dtConverter
                },
                //忽略深度循环
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
        }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(new CDNHelper());
        IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"
        };

        services.AddMvc();
        services.AddSignalR(o =>
        {
        }).AddJsonProtocol(j =>
        {
            j.PayloadSerializerSettings.Converters.Add(dateConverter);
        });
    }
        public string ConvertToJsonSingle(object obj)
        {
            IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();

            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string JsonStr = "";

            List <RealtimeData> list = new List <RealtimeData>();

            for (int i = 0; i < ((List <DataList>)obj).Count; i++)
            {
                list.Add(((List <DataList>)obj)[i].realtime_dataObj);
            }
            JsonStr = JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented, timeFormat);
            return(JsonStr);
        }
Example #14
0
        public IActionResult Index(string filterJson)
        {
            HtmlTemplateFilterVM model = null;

            if (!string.IsNullOrEmpty(filterJson))
            {
                var dateTimeConverter = new IsoDateTimeConverter()
                {
                    DateTimeFormat = FormattingConstant.NormalDateFormat
                };
                model = JsonConvert.DeserializeObject <HtmlTemplateFilterVM>(filterJson, dateTimeConverter);
            }
            SetViewbag();
            ViewBag.breadcrumbs = commonService.Breadcrumbs_HtmlTemplate().DeleteOrDisableLast();
            return(View(model));
        }
Example #15
0
 public static string GetHonorInfo(List <honor> honorList, IhonorService HonorService, IhonorparticipantmemberService HonorparticipantmemberService, IteamService TeamService, IpersonalinformationService PersonalinformationService)
 {
     try
     {
         //var honorList = HonorService.LoadEntities(h => true).ToList();
         List <Model.ViewModel.HonorStripModel.Honor> HonorList = new List <Model.ViewModel.HonorStripModel.Honor>();
         //获取荣耀表中所有的荣耀  (荣耀名称、上传时间、荣耀简介)
         foreach (var honor in honorList)
         {
             List <int> honorMemberId = new List <int>();
             List <Model.ViewModel.HonorStripModel.Person> personList = new List <Model.ViewModel.HonorStripModel.Person>();
             Model.ViewModel.HonorStripModel.Honor         honors     = new Model.ViewModel.HonorStripModel.Honor();
             honors.honorId        = honor.ID;                           //荣耀ID
             honors.honorLogo      = honor.vcPreviewAddress;             //荣耀LOGO
             honors.honorName      = honor.vcHonorName;                  //荣耀名称
             honors.honorSubmit    = (System.DateTime)honor.dSubmitTime; //荣耀上传时间
             honors.guidTeacher    = honor.vcGuideTeacher;               //荣耀指导老师
             honors.honorIntroduce = honor.vcHonorIntroduce;             //荣耀简介
             var team = TeamService.LoadEntities(t => t.ID == honor.iTeamID).FirstOrDefault();
             honors.honorTeam = team.vcTeamName;                         //所属团队
             var honorMemberList = HonorparticipantmemberService.LoadEntities(hm => hm.iHonorID == honor.ID).ToList();
             foreach (var honorMember in honorMemberList)
             {
                 honorMemberId.Add((int)honorMember.iUserID);
                 honors.unperHonorName = honorMember.vcNonTeamMember;
             }
             var perInfomation = PersonalinformationService.LoadPersonalInformationList(honorMemberId).ToList();
             foreach (var perInfo in perInfomation)
             {
                 Model.ViewModel.HonorStripModel.Person person = new Model.ViewModel.HonorStripModel.Person();
                 person.Name = perInfo.vcName;
                 personList.Add(person);
             }
             honors.personList = personList;
             HonorList.Add(honors);
         }
         var timerConverter = new IsoDateTimeConverter {
             DateTimeFormat = "yyyy-MM-dd"
         };
         string jsonTxt = JsonConvert.SerializeObject(HonorList, Newtonsoft.Json.Formatting.Indented);
         return(jsonTxt);
     }
     catch (Exception)
     {
         return("网络不稳定,请稍后重试");
     }
 }
        /// <summary>
        /// 获取团队表中的所有内容   分页
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTeamALL()
        {
            string jsonTxt = null;
            List <Model.ViewModel.BackDataModel.TeamAll> teamAllList = new List <Model.ViewModel.BackDataModel.TeamAll>();

            Model.ViewModel.BackDataModel.TeamAll team = new Model.ViewModel.BackDataModel.TeamAll();
            try
            {
                var teamAll = TeamService.LoadEntities(t => true).ToList();
                if (teamAll != null)
                {
                    foreach (var t in teamAll)
                    {
                        team.teamId      = t.ID;
                        team.Logo        = t.vcTeamLogoAddress;
                        team.teamName    = t.vcTeamName;
                        team.guidTeacher = t.vcGuideTeacher;
                        team.SetupTime   = (DateTime)t.dTeamSetupTime;
                        team.teamMain    = t.vcTeamMain;
                        if (t.bCheckedTeacher == true && t.bCheckedcounselor == true)
                        {
                            team.check = "已审核";
                        }
                        else
                        {
                            team.check = "未审核";
                        }
                        team.teamIntroduce = t.vcTeamIntroduce;
                        teamAllList.Add(team);
                    }
                    var timerConverter = new IsoDateTimeConverter {
                        DateTimeFormat = "yyyy-MM-dd"
                    };
                    jsonTxt = JsonConvert.SerializeObject(teamAllList, Newtonsoft.Json.Formatting.Indented);
                }
                else
                {
                    jsonTxt = "空空如也";
                }
            }
            catch (Exception ex)
            {
                jsonTxt = "网络出现异常" + ex.ToString();
            }

            return(Content(jsonTxt));
        }
Example #17
0
        /// <summary>
        /// Create new asset on Raspberry using API
        /// </summary>
        /// <param name="a">New asset to create on Raspberry</param>
        /// <returns></returns>
        public async Task CreateAsset(Asset a)
        {
            Asset returnedAsset                  = new Asset();
            JsonSerializerSettings settings      = new JsonSerializerSettings();
            IsoDateTimeConverter   dateConverter = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"
            };

            settings.Converters.Add(dateConverter);

            string json     = JsonConvert.SerializeObject(a, settings);
            var    postData = $"model={json}";
            var    data     = System.Text.Encoding.UTF8.GetBytes(postData);

            string resultJson = string.Empty;
            string parameters = $"/api/{this.ApiVersion}assets";

            try
            {
                HttpClient  client  = new HttpClient();
                HttpContent content = new ByteArrayContent(data, 0, data.Length);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                using (HttpResponseMessage response = await client.PostAsync(this.HttpLink + parameters, content))
                {
                    resultJson = await response.Content.ReadAsStringAsync();
                }

                if (!resultJson.Equals(string.Empty))
                {
                    returnedAsset = JsonConvert.DeserializeObject <Asset>(resultJson, settings);
                }
            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                    using (var reader = new StreamReader(stream))
                    {
                        throw new Exception(reader.ReadToEnd(), ex);
                    }
            }
            catch (Exception ex)
            {
                throw new Exception("Error while creating asset.", ex);
            }
        }
Example #18
0
 public static string Serialize(object @object, string dateTimeFormat)
 {
     try
     {
         JsonConverter[]      converters = new JsonConverter[1];
         IsoDateTimeConverter converter  = new IsoDateTimeConverter {
             DateTimeFormat = dateTimeFormat
         };
         converters[0] = converter;
         return(JsonConvert.SerializeObject(@object, converters));
     }
     catch (Exception exception)
     {
         Logger.WriteLog(Logger.LogType.Error, exception.Message);
         return(string.Empty);
     }
 }
Example #19
0
 public static T Deserialize <T>(string jsonString, string dateTimeFormat)
 {
     try
     {
         JsonConverter[]      converters = new JsonConverter[1];
         IsoDateTimeConverter converter  = new IsoDateTimeConverter {
             DateTimeFormat = dateTimeFormat
         };
         converters[0] = converter;
         return(JsonConvert.DeserializeObject <T>(jsonString, converters));
     }
     catch (Exception exception)
     {
         Logger.WriteLog(Logger.LogType.Error, exception.Message);
         return(default(T));
     }
 }
Example #20
0
        public static void Configure(IAppBuilder appBuilder, ILifetimeScope container)
        {
            var config = new HttpConfiguration();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            var requireHttpsAttribute = new RequireHttpsAttribute();

#if !DEBUG
            config.Filters.Add(requireHttpsAttribute);
#endif

            // return JSON instead of XML by default
            var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes
                             .FirstOrDefault(t => t.MediaType == "application/xml");
            config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

            // use camelCase in JSON
            var jsonFormatter = config.Formatters.OfType <JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            // standardize datetime format
            jsonFormatter.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
            {
                DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"
            };
            jsonFormatter.SerializerSettings.Converters.Add(dateConverter);

            appBuilder.UseAutofacWebApi(config);
            appBuilder.UseWebApi(config);

            appBuilder.UseFileServer(new FileServerOptions
            {
                EnableDefaultFiles = false,
                RequestPath        = new PathString("/images")
            });
        }
Example #21
0
        public static string NewQuerySubscribeInfo()
        {
            WGUserEn user = (WGUserEn)HttpContext.Current.Session["user"];

            if (user == null || user.GwyUserID <= 0)
            {
                return("");
            }
            DataTable infodt = SubscribeModel.getNewSubscribeInfo_Order(user.GwyUserID);

            //DataTable infodt = SubscribeModel.getNewSubscribeInfo_Order(1124);

            if (infodt == null || infodt.Rows.Count == 0)
            {
                return("");
            }
            try
            {
                foreach (DataRow dr in infodt.Rows)
                {
                    if (string.IsNullOrEmpty(dr["divideno"].ToString2()))
                    {
                        dr["divideno"] = "";
                    }
                    if (string.IsNullOrEmpty(dr["logisticsname"].ToString2()))
                    {
                        dr["logisticsname"] = "";
                    }
                    if (string.IsNullOrEmpty(dr["contractno"].ToString2()))
                    {
                        dr["contractno"] = "";
                    }
                    dr["declstatus"] = SwitchHelper.switchValue("declstatus", dr["declstatus"].ToString2());
                    dr["inspstatus"] = SwitchHelper.switchValue("inspstatus", dr["inspstatus"].ToString2());
                }
                IsoDateTimeConverter iso = new IsoDateTimeConverter();//序列化JSON对象时,日期的处理格式
                iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                string json = JsonConvert.SerializeObject(infodt, iso);
                return(json);
            }
            catch (Exception e)
            {
                LogHelper.Write("MyBusiness_QueryData:" + e.Message);
                return("");
            }
        }
Example #22
0
        public static string ToJson(this object ob, string dateTimeFormat = null)
        {
            if (ob == null)
            {
                return(null);
            }
            if (dateTimeFormat == null)
            {
                dateTimeFormat = DateTimeFormats.DateFormat;
            }
            var isoConvert = new IsoDateTimeConverter();

            isoConvert.DateTimeFormat = dateTimeFormat;
            string result = JsonConvert.SerializeObject(ob, isoConvert);

            return(result);
        }
Example #23
0
        public static void SeedUsers(UserManager <User> userManager, RoleManager <Role> roleManager)
        {
            var roles = new List <Role>()
            {
                new Role {
                    Name = "Admin"
                },
                new Role {
                    Name = "Moderator"
                },
                new Role {
                    Name = "Member"
                },
                new Role {
                    Name = "Hacker"
                },
            };

            foreach (var role in roles)
            {
                roleManager.CreateAsync(role).Wait();
            }

            if (!userManager.Users.Any())
            {
                var userJsonData      = System.IO.File.ReadAllText("Data/SeedData/users.json");
                var format            = "dd-MM-yyyy";
                var dateTimeConverter = new IsoDateTimeConverter {
                    DateTimeFormat = format
                };
                var users = JsonConvert.DeserializeObject <List <User> >(userJsonData, dateTimeConverter);
                foreach (var user in users)
                {
                    userManager.CreateAsync(user, "password123").Wait();
                    userManager.AddToRoleAsync(user, "Member").Wait();
                }

                //For testing only
                var admin = new User()
                {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.CreateAsync(admin, "password123").Wait();
                userManager.AddToRolesAsync(admin, new[] { "Admin", "Moderator" }).Wait();
            }
        }
Example #24
0
    public static string ToJson(object entity, bool camelCase = false)
    {
        var converter = new IsoDateTimeConverter();

        converter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        var serializer = new JsonSerializer();

        serializer.Converters.Add(converter);
        if (camelCase)
        {
            serializer.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
        }
        var sb = new StringBuilder();

        serializer.Serialize(new JsonTextWriter(new StringWriter(sb)), entity);
        return(sb.ToString());
    }
Example #25
0
            public override void ExecuteResult(ControllerContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException("context");
                }

                HttpResponseBase response = context.HttpContext.Response;

                if (Data != null)
                {
                    var timeConverter = new IsoDateTimeConverter {
                        DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                    };                                                                                      //这里使用自定义日期格式,默认是ISO8601格式
                    response.Write(JsonConvert.SerializeObject(Data, Formatting.Indented, timeConverter));
                }
            }
Example #26
0
        /// <summary>
        /// Object To JqGridJson
        /// </summary>
        /// <param name="value"></param>
        /// <param name="records">总记录数</param>
        /// <param name="currPage">当前页码</param>
        /// <param name="pageTotal">总页数</param>\
        /// <param name="dateTimeFormat">日期格式化</param>
        /// <param name="columnsLowerOrUpper">是否把列名转换大小写,-1:不转换、0:转换小写、1:转换成大写;</param>
        /// <returns>{page:当前页,total:总页数,records:总记录数,rows:[数据列]}</returns>
        public static string ToJqGridJsonFromObject(this Object value, int records = -1, int currPage = 1, int pageTotal = 1, JsonDateTimeFormat dateTimeFormat = JsonDateTimeFormat.IsoDateTimeLong, int columnsLowerOrUpper = 0, string userdata = "")
        {
            if (null == value)
            {
                return("{page:0,total:0,records:0,rows:[]}");
            }

            StringBuilder jsonBuilder = new StringBuilder();

            jsonBuilder.Append("{");
            jsonBuilder.Append("\"page\":" + currPage + ",\"total\":" + pageTotal + ",\"records\":" + records + ",\"rows\"");
            jsonBuilder.Append(":");

            switch (dateTimeFormat)
            {
            case JsonDateTimeFormat.JavaScriptDateTime:
                jsonBuilder.Append(JsonConvert.SerializeObject(value, new JavaScriptDateTimeConverter()));
                break;

            case JsonDateTimeFormat.IsoDateTime:
                jsonBuilder.Append(JsonConvert.SerializeObject(value, new IsoDateTimeConverter()));
                break;

            case JsonDateTimeFormat.IsoDateTimeShort:

                IsoDateTimeConverter timeConverter01 = new IsoDateTimeConverter();
                timeConverter01.DateTimeFormat = "yyyy-MM-dd";
                jsonBuilder.Append(JsonConvert.SerializeObject(value, timeConverter01));
                break;

            case JsonDateTimeFormat.IsoDateTimeLong:
            default:
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
                timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
                jsonBuilder.Append(JsonConvert.SerializeObject(value, timeConverter));
                break;
            }

            if (false == userdata.AsNullOrWhiteSpace())
            {
                jsonBuilder.AppendFormat(", \"userdata\":\"{0}\"", userdata);
            }

            jsonBuilder.Append("}");
            return(jsonBuilder.ToString());
        }
        public async Task Invoke(HttpContext context)
        {
            var bodyStr = "";
            var req     = context.Request;

            // Allows using several time the stream in ASP.Net Core
            req.EnableRewind();

            // Arguments: Stream, Encoding, detect encoding, buffer size
            // AND, the most important: keep stream opened
            using (StreamReader reader
                       = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
            {
                bodyStr = reader.ReadToEnd();
            }

            // Rewind, so the core is not lost when it looks the body for the request
            req.Body.Position = 0;

            var c = new IsoDateTimeConverter();

            try
            {
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);

                context.Response.StatusCode = 500;
            }

            if (!context.Response.HasStarted)
            {
                if (context.Response.Body.CanWrite && context.Response.HasStarted) // no content
                {
                    context.Response.ContentType = "application/json";

                    var response = new ApiResponse(context.Response.StatusCode);

                    var json = JsonConvert.SerializeObject(response);

                    await context.Response.WriteAsync(json);
                }
            }
        }
Example #28
0

        
Example #29
0
        /// <summary>
        /// 配置服务
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            //添加跨域策略
            services.AddCors(options => options.AddPolicy(typeof(Startup).FullName,
                                                          policyBuilder =>
            {
                policyBuilder.AllowAnyMethod();
                policyBuilder.AllowAnyHeader();
                policyBuilder.AllowCredentials();
                policyBuilder.SetIsOriginAllowed(_ => true);
            }));

            //添加Swagger
            services.AddSwaggerGen(options =>
            {
                OpenApiInfo apiInfo = new OpenApiInfo
                {
                    Version = "v1.0",
                    Title   = "身份认证系统 WebApi 接口文档"
                };

                string xmlFileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                string xmlFilePath = Path.Combine(AppContext.BaseDirectory, xmlFileName);

                options.SwaggerDoc("v1.0", apiInfo);
                options.IncludeXmlComments(xmlFilePath);
            });

            //添加过滤器
            services.AddControllers(options =>
            {
                options.Filters.Add <WebApiAuthenticationFilter>();
                options.Filters.Add <WebApiExceptionFilter>();
            }).AddNewtonsoftJson(options =>
            {
                //Camel命名设置
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

                //日期时间格式设置
                IsoDateTimeConverter dateTimeConverter = new IsoDateTimeConverter()
                {
                    DateTimeFormat = CommonConstants.DateTimeFormat
                };
                options.SerializerSettings.Converters.Add(dateTimeConverter);
            });
        }
Example #30
0
 /// <summary>
 ///     Json序列化对象
 /// </summary>
 /// <typeparam name="T">对象类型</typeparam>
 /// <param name="t">对象</param>
 /// <returns></returns>
 public static string JsonSerialize <T>(T t)
 {
     try
     {
         //var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
         //return serializer.Serialize(t);
         IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
         timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
         return(JsonConvert.SerializeObject(t, Newtonsoft.Json.Formatting.None, timeFormat));
     }
     catch (Exception ex)
     {
     }
     return(string.Empty);
     //return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(t);
     //return JavaScriptConvert.SerializeObject(t);
 }