.net报错异常及常用功能处理总结(持续更新)

.net报错异常及常用功能处理总结---持续更新

1. WebApi dynamic传参解析结果中ValueKind = Object处理方法

问题描述
  • WebApi dynamic传参解析结果中ValueKind处理方法
  • System.Text.Json类库进行json转化时 ValueKind:Object 问题
  • .NET dynamic传参中带有ValueKind属性处理方法
  • 动态 c# ValueKind = Object
  • 前端传参给后端以后,发现接受到的参数是这个样子ValueKind = Object : "{"TEST":{"A":1}}"
方案1:(推荐,改动很小)

备注: 数据解析以后如果有循环问题,可以参考下面的问题4

复制代码
dynamic dynParam = JsonConvert.DeserializeObject(Convert.ToString(params));
方案2:

将默认的序列化程序System.Text.Json替换为Newtonsoft.Json

  • 1.NuGet引入包:Microsoft.AspNetCore.Mvc.NewtonsoftJson

  • 2.Startup添加命名空间:using Newtonsoft.Json.Serialization;

  • 3.Startup类的ConfigureServices方法中添加代码:

    //添加对象序列化程序为Newtonsoft.Json
    services.AddControllers().AddNewtonsoftJson(options =>
    {
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    });

2.C# .net多层循环嵌套结构数据对象如何写对象动态属性赋值

问题描述

下面是一个案例,根据anonymousObject 的属性,动态赋值projectEntity的属性,且对象为一个多层嵌套结构,因为我平时写js比较多,平时使用JavaScript函数搞对象动态赋值比较多,当转化为.net代码后,我们可以看一下对比:

JavaScript动态属性赋值
复制代码
function UpdateXiaojinTestVaue() {
  const TestBool = {
    NotRequired: 0,
    Required: 1,
  };
  var anonymousObject = {
    OneXiaojinTest: {
      One: TestBool.NotRequired,
      Two: TestBool.NotRequired,
      Three: TestBool.NotRequired,
      Four: TestBool.NotRequired,
      Five: TestBool.Required,
    },
    TwoXiaojinTest: {
      One: TestBool.NotRequired,
      Two: TestBool.NotRequired,
      Three: TestBool.Required,
    },
  };

  var projectEntity = {
    XiaojinTest: {
      OneXiaojinTest: {
        One: TestBool.Required,
        Two: TestBool.Required,
        Three: TestBool.Required,
        Four: TestBool.Required,
        Five: TestBool.Required,
      },
      TwoXiaojinTest: {
        One: TestBool.NotRequired,
        Two: TestBool.NotRequired,
        Three: TestBool.Required,
      },
      a: { aa: TestBool.Required },
      b: { bb: TestBool.Required },
    },
  };
  Object.keys(anonymousObject).forEach(function (key) {
    Object.keys(anonymousObject[key]).forEach(function (key2) {
        
      if (projectEntity.XiaojinTest[key]) {
        projectEntity.XiaojinTest[key][key2] = anonymousObject[key][key2];
        console.log(anonymousObject[key])
        console.log('-----------------------')
        console.log(anonymousObject[key])
        console.log('+++++++++++++++++++++++++++++++++++++')
      }
    });
  });
  console.log(projectEntity)
}
UpdateXiaojinTestVaue()
.net动态属性赋值

UpdateTriggerControlVaue JS 转换为.NET C#代码,转化后

复制代码
using System;
using System.Collections.Generic;

public class TestBool
{
    public const int NotRequired = 0;
    public const int Required = 1;
}

public class Program
{
    public static void Main()
    {
        UpdateXiaojinTestValue();
    }

    public static void UpdateXiaojinTestValue()
    {
        var anonymousObject = new
        {
            OneXiaojinTest = new
            {
                One = TestBool.NotRequired,
                Two = TestBool.NotRequired,
                Three = TestBool.NotRequired,
                Four = TestBool.NotRequired,
                Five = TestBool.Required
            },
            TwoXiaojinTest = new
            {
              One = TestBool.NotRequired,
              Two = TestBool.NotRequired,
              Three = TestBool.Required,
            },
        };

        var projectEntity = new
        {
            XiaojinTest = new
            {
                OneXiaojinTest = new
                {
                    One = TestBool.Required,
                    Two = TestBool.Required,
                    Three = TestBool.Required,
                    Four = TestBool.Required,
                    Five = TestBool.Required,
                    Requirement = TestBool.Required,
                    Testing = TestBool.Required,
                    ThirdParthDueDiligence = TestBool.Required,
                },
                TwoXiaojinTest = new
                {
                  One = TestBool.NotRequired,
                  Two = TestBool.NotRequired,
                  Three = TestBool.Required,
                },
                a = new { aa = TestBool.Required },
                b = new { bb = TestBool.Required },
            },
        };

        foreach (var key in anonymousObject.GetType().GetProperties())
        {
            var subAnonymousObject = key.GetValue(anonymousObject);

            foreach (var key2 in subAnonymousObject.GetType().GetProperties())
            {
                if (projectEntity.XiaojinTest.GetType().GetProperty(key.Name)?.GetValue(projectEntity.XiaojinTest) is not null)
                {
                    var targetSubObject = projectEntity.XiaojinTest.GetType().GetProperty(key.Name).GetValue(projectEntity.XiaojinTest);
                    targetSubObject.GetType().GetProperty(key2.Name)?.SetValue(targetSubObject, key2.GetValue(subAnonymousObject));

                    Console.WriteLine(subAnonymousObject);
                    Console.WriteLine("-----------------------");
                    Console.WriteLine(subAnonymousObject);
                    Console.WriteLine("+++++++++++++++++++++++++++++++++++++");
                }
            }
        }

        Console.WriteLine(projectEntity);
    }
}

3.Object.GetType().GetProperty().GetValue()读取对象报错,无法获取Json转化对象的属性和值怎么办,。net C# .GetType().GetProperties()报错失效

问题描述

接上题,正常情况下,声明的对象可以使用Object.GetType().GetProperty().GetValue()或者.GetType().GetProperties()读取属性和值,但是如果是JSON格式,读取就会有异常,如何处理呢?

解决方案
复制代码
 var result = JsonConvert.DeserializeObject<IDictionary<string, object>>(Convert.ToString(params));
 foreach (var item in result.Keys)
 {
     var value = result[item];
     Console.WriteLine("------item----------------");
     Console.WriteLine(item);
     Console.WriteLine("------value----------------");
     Console.WriteLine(value);
 }

4.如何循环各种类型的对象数据?

问题描述

第一步先通过**GetType()**方法来获取对象的类型,根据数据类型不同,循环方法也不一样,下面是我今天熬夜到凌晨四点多总结出来的结果,原谅我是一个JS爱好者,第一次搞这个遇到了很多问题,所以真的是熬死我:

  • (GetType) 获取动态Json对象属性值的方法
  • .net获取动态属性值的方法
解决方案1 类型:new{} new出来的自定义对象
复制代码
 // 对象类型01
 // -- 类型:new{} new出来的自定义对象
 // -- 获取属性:key.Name
 // -- 获取值:key.GetValue(params)
 // -- 循环方法:foreach (var key in xiaojinObject.GetType().GetProperties()) 


 foreach (var key in anonymousObject.GetType().GetProperties())
        {
            var subAnonymousObject = key.GetValue(anonymousObject);

            foreach (var key2 in subAnonymousObject.GetType().GetProperties())
            {
                if (projectEntity.XiaojinTest.GetType().GetProperty(key.Name)?.GetValue(projectEntity.XiaojinTest) is not null)
                {
                    var targetSubObject = projectEntity.XiaojinTest.GetType().GetProperty(key.Name).GetValue(projectEntity.XiaojinTest);
                    targetSubObject.GetType().GetProperty(key2.Name)?.SetValue(targetSubObject, key2.GetValue(subAnonymousObject));

                    Console.WriteLine(subAnonymousObject);
                    Console.WriteLine("-----------------------");
                    Console.WriteLine(subAnonymousObject);
                    Console.WriteLine("+++++++++++++++++++++++++++++++++++++");
                }
            }
        }
解决方案2 类型:System.Collections.Generic.Dictionary`2[System.String,System.Object]
复制代码
 // 对象类型02
 // -- 类型:System.Collections.Generic.Dictionary`2[System.String,System.Object]
 // -- 获取属性:key
 // -- 获取值:params[key]
 // -- 循环方法:foreach (var key in xiaojinObject.Keys) 
解决方案3 类型:Newtonsoft.Json.Linq.JObject
复制代码
 // 对象类型03
 // -- 类型:Newtonsoft.Json.Linq.JObject
 // -- 获取属性:item.Name
 // -- 获取值:item.Value
 // -- 循环方法:foreach (JProperty item in xiaojinObject.Properties())

5. C# .net如何获取某个对象的类型,GetType() typeof() is的区别

获取:通过**GetType()**方法来获取对象的类型
复制代码
Console.WriteLine("------11----------------");
Console.WriteLine(anonymousObject.GetType());
Console.WriteLine("---------------22--------");
Console.WriteLine(subAnonymousObject.GetType());
对比方案1:通过**typeof()**来判断是否是这个类型
复制代码
if (abc.GetType() == typeof(Double))//判断abc是否是Double类型
{
     Console.WriteLine("abc是Double类型");
}
对比方案2:is关键字
复制代码
// 格式
[------要判断的对象------] is [------要判断的数据类型------]

// 举例
if (abc is Double)//判断abc是否是双精度浮点类型
            {
                Console.WriteLine("abc是Double类型");
            }

6.couldnt install microsoft.visualcpp.redist.14

复制代码
Something went wrong with the install.

You can troubleshoot the package failures by:

    1. Search for solutions using the search URL below for each package failure
    2. Modify your selections for the affected workloads or components and then retry the installation
    3. Remove the product from your machine and then install again

If the issue has already been reported on the Developer Community, you can find solutions or workarounds there. If the issue has not been reported, we encourage you to create a new issue so that other developers will be able to find solutions or workarounds. You can create a new issue from within the Visual Studio Installer in the upper-right hand corner using the "Provide feedback" button.

================================================================================

Package 'Microsoft.VisualCpp.Redist.14,version=14.38.33130,chip=x86' failed to install.
    Search URL
        https://aka.ms/VSSetupErrorReports?q=PackageId=Microsoft.VisualCpp.Redist.14;PackageAction=Install;ReturnCode=-2147023274
    Details
        Command executed: "c:\windows\syswow64\\windowspowershell\v1.0\powershell.exe" -NoLogo -NoProfile -Noninteractive -ExecutionPolicy Unrestricted -InputFormat None -Command "& """C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualCpp.Redist.14,version=14.38.33130,chip=x86\VCRedistInstall.ps1""" -PayloadDirectory """C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft.VisualCpp.Redist.14,version=14.38.33130,chip=x86""" -Architecture x86 -Logfile """C:\Users\XX\AppData\Local\Temp\dd_setup_20240119115035_255_Microsoft.VisualCpp.Redist.14.log"""; exit $LastExitCode"
        Return code: -2147023274
        Return code details: Error opening installation log file. Verify that the specified log file location exists and that you can write to it.
    Log
解决方案1
  • 找到这个目录C:\ProgramData\Microsoft\VisualStudio\Packages
  • 直接搜索VC_redist关键词
  • 找到这个VC_redist.x64.exe文件,一般会有两个,直接全部双击安装
  • 返回VS installer 界面点击:更多---修复


解决方案2
  • 当遇到报错,点击错误信息下面的查看日志选项,打开日志文件(就像上面粘贴的那些异常信息)
  • 在错误日志中寻找安装文件的路径,类似于:C:\ProgramData\Microsoft\VisualStudio\Packages\Microsoft. visualcp . redist .14. latest,version=xx.xx.xxxxx
  • 打开此路径位置
  • 看到一个VC redist.xxx.exe
  • 安装运行它
  • 关机重启
  • 重新运行VS installer 界面点击:更多---修复
  • 今天就写到这里啦~
  • 小伙伴们,( ̄ω ̄( ̄ω ̄〃 ( ̄ω ̄〃)ゝ我们明天再见啦~~
  • 大家要天天开心哦

欢迎大家指出文章需要改正之处~

学无止境,合作共赢

欢迎路过的小哥哥小姐姐们提出更好的意见哇~~
相关推荐
流水线上的指令侠20 小时前
C# 实战:从 0 到 1 搭建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目
功能测试·ui·c#·自动化·wpf·visual studio
0和1的舞者20 小时前
技术优化手册:从工具类到 MyBatis 配置与业务逻辑
java·后端·学习·开发·知识
gc_229921 小时前
学习C#调用OpenXml操作word文档的基本用法(20:学习嵌入文件类)
c#·word·openxml·嵌入文档
玩泥巴的21 小时前
如何实现一套.net系统集成多个飞书应用
c#·.net·二次开发·飞书
ghie909021 小时前
基于C#实现俄罗斯方块游戏
开发语言·游戏·c#
ccut 第一混21 小时前
C# 基于 RS485 与设备通讯(以照度计为例子)
c#·rs485
我爱娃哈哈21 小时前
SpringBoot 实现 RSA+AES 自动接口解密
java·spring boot·后端
崎岖Qiu21 小时前
SpringBoot:基于注解 @PostConstruct 和 ApplicationRunner 进行初始化的区别
java·spring boot·后端·spring·javaee
沈雅馨21 小时前
SQL语言的云计算
开发语言·后端·golang