第二十九节: Core MVC零散总结(各种目录、内外网ip、新序列化、全局处理返回值)

一. 总结1

1. IWebHostEnvironment获取常用属性

(1).获取项目的根目录

  _env.ContentRootPath 等价于 Directory.GetCurrentDirectory()

(2).获取项目下wwwroot目录

   _env.WebRootPath

(3).获取项目最终dll的目录(拼接)

   _env.ContentRootPath + @"\bin\Debug\netcoreapp3.1\"

补充:通过 AppContext.BaseDirectory; 直接获取最终dll文件所在的目录。

(4).获取项目名称

  _env.ApplicationName

(5).获取运行环境

  _env.EnvironmentName

代码分享:

 {
                //项目的绝对目录
                var d1 = _env.ContentRootPath;
                var d2 = Directory.GetCurrentDirectory();
                //项目的WebRoot目录
                var d3 = _env.WebRootPath;
                //最终dll文件的目录,拼接
                var d4 = _env.ContentRootPath + @"\bin\Debug\netcoreapp3.1\";
                var d44 = AppContext.BaseDirectory;   //直接就可以获取
                //项目名称
                var d5 = _env.ApplicationName;
                //项目运行环境
                var d6 = _env.EnvironmentName;

                ViewBag.d1 = d1;
                ViewBag.d2 = d2;
                ViewBag.d3 = d3;
                ViewBag.d4 = d4;
                ViewBag.d44 = d44;
                ViewBag.d5 = d5;
                ViewBag.d6 = d6;
}
View Code

运行效果:

2. 获取内外网ip地址和端口

(1).获取请求的外网ip和端口:this.HttpContext.Connection.RemoteIpAddress; 和 this.HttpContext.Connection.RemotePort;

(2).获取本地内网ip和端口: this.HttpContext.Connection.LocalIpAddress; 和 this.HttpContext.Connection.LocalPort;

代码分享:

 public class FirstController : Controller
    {
        public IActionResult Index()
        {
   
            //2. 获取内外网ip和端口
            {
                var p1 = this.HttpContext.Request.Method;
                //外网ip,必须部署在外网服务器上.  Server-client如果在一个内网中,获取的还是内网地址
                var p2 = this.HttpContext.Connection.RemoteIpAddress;
                var p3 = this.HttpContext.Connection.RemotePort;

                //获取本地ip地址和端口,即项目部署在哪,获取的就是哪的。
                var p4 = this.HttpContext.Connection.LocalIpAddress;
                var p5 = this.HttpContext.Connection.LocalPort;

                ViewBag.p1 = p1;
                ViewBag.p2 = p2;
                ViewBag.p3 = p3;
                ViewBag.p4 = p4;
                ViewBag.p5 = p5;
            }

            return View();
        }
    }
View Code

 3.  新的序列化

 使用Core 3.x内置的System.Text.Json进行序列化和反序列化。

 封装代码如下:

  /// <summary>
    /// Json的序列化和反序列化
    /// 依赖程序集:Core 3.x内置的System.Text.Json
    /// </summary>
    public class JsonHelp
    {
 
        #region 01-将JSON转换成JSON字符串
        /// <summary>
        ///将JSON转换成JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonString<T>(T obj)
        {
            //return JsonConvert.SerializeObject(obj);  //Newtonsoft.Json写法
            return JsonSerializer.Serialize(obj);
           
        }
        #endregion

        #region 02-将字符串转换成JSON对象
        /// <summary>
        /// 将字符串转换成JSON对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public static T ToObject<T>(string content)
        {
            //return JsonConvert.DeserializeObject<T>(content);  //Newtonsoft.Json写法
            return JsonSerializer.Deserialize<T>(content);         
        }
        #endregion
    }
View Code

调用代码如下:

  ErrorViewModel model = new ErrorViewModel()
                {
                    RequestId = "111"
                };
                //序列化
                string str = JsonHelp.ToJsonString(model);

                //反序列化
                ErrorViewModel newModel = JsonHelp.ToObject<ErrorViewModel>(str);
View Code

 在实际项目中使用了一下,不成熟,出现了各种问题,很坑比。 相关问题可以参照:https://www.cnblogs.com/dudu/p/11562019.html

 

二. 全局处理返回值

旧版MVC中基于过滤器处理可参考:

 https://www.cnblogs.com/yaopengfei/p/9518725.html

1.背景与目标

 在Core Mvc 3.x版本中,通过return Json的模式返回给前端, DateTime类型不友好(当然可以在后台强转,或者在前端转换),而且会将参数默认成首字母小写, 不是我们想要的,我们需要的是DateTime指定格式,参数名传什么显示什么。

如下面接口,在3.x版本中的返回值如图:

 /// <summary>
        /// 测试各种返回格式
        /// (全局配置)
        /// </summary>
        /// <returns></returns>
        public IActionResult Test3()
        {
            List<string> list = new List<string>();

            return Json(new
            {
                Id1 = "1235456",
                id2 = "2343545",
                txt1 = "xxxx",
                txt2 = list,
                time1 = DateTime.Now,
                time2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });
        }

如图:

2. 方案1

 基于Core自带的【System.Text.Json】程序集实现.

日期格式转换类

    /// <summary>
    /// 日期格式转换类
    /// </summary>
    public class DatetimeJsonConverter : System.Text.Json.Serialization.JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                if (DateTime.TryParse(reader.GetString(), out DateTime date))
                    return date;
            }
            return reader.GetDateTime();
        }
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

ConfigureService

  public void ConfigureServices(IServiceCollection services)
  {
            //方案1:
            services.AddControllersWithViews().AddJsonOptions(options =>
            {
                //格式化日期时间格式
                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                //参数格式首字母小写(=null 则表示参数原样输出)
                //options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                //取消Unicode编码
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                //忽略空值
                options.JsonSerializerOptions.IgnoreNullValues = true;
                //允许额外符号
                options.JsonSerializerOptions.AllowTrailingCommas = true;
                //反序列化过程中属性名称是否使用不区分大小写的比较
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
            });

  }

处理后的返回值 

3. 方案2

 基于程序集【Microsoft.AspNetCore.Mvc.NewtonsoftJson】实现,需要通过Nuget安装。

ConfigureService代码:

 public void ConfigureServices(IServiceCollection services)
 {
            //方案2:
            services.AddControllersWithViews().AddNewtonsoftJson(options =>
            {
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //数据格式首字母小写
                //options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //数据格式按原样输出
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //忽略空值
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            });

  }

处理后的返回值:

 

 

 

 

 

 

 

 

 

 

 

 

 

!

  • 作       者 : Yaopengfei(姚鹏飞)
  • 博客地址 : http://www.cnblogs.com/yaopengfei/
  • 声     明1 : 如有错误,欢迎讨论,请勿谩骂^_^。
  • 声     明2 : 原创博客请在转载时保留原文链接或在文章开头加上本人博客地址,否则保留追究法律责任的权利。
 

 

posted @ 2020-02-25 16:54  Yaopengfei  阅读(700)  评论(3编辑  收藏  举报