【知识笔记】Debugging

1、启动调试出现 没法启动程序 当前状态中是非法

VS工具--选项--调试--常规--启用asp.net的JavaScript调试(chrome和ie)去掉勾选css

2、web.config中<customErrors>报错

<customErrors>节点用于定义一些自定义错误信息的信息。html

此节点有Mode和defaultRedirect两个属性,其中git

defaultRedirect属性是一个可选属性,表示应用程序发生错误时重定向到的默认URL,若是没有指定该属性则显示通常性错误;web

Mode属性是一个必选属性,它有三个可能值,它们所表明的意义分别以下:
Mode 说明
On 表示在本地和远程用户都会看到自定义错误信息。
Off 禁用自定义错误信息,本地和远程用户都会看到详细的错误信息
RemoteOnly 表示本地用户将看到详细错误信息,而远程用户将会看到自定义错误信息。
这里有必要说明一下本地用户和远程用户的概念。当咱们访问asp.net应用程时所使用的机器和发布asp.net应用程序所使用的机器为同一台机器时成为本地用户,反之则称之为远程用户。sql

开发调试阶段为了便于查找错误Mode属性建议设置为Off,而在部署阶段应将Mode属性设置为On或者RemoteOnly,以免这些详细的错误信息暴露了程序代码细节从而引来黑客的入侵。chrome

因此想看具体的错误,有两种方式:将mode设置为Off,或者直接在服务器上复现刚才发生错误的操做,看详细的错误信息。数据库

参考:关于web.config中<customErrors>节点说明json

 

3、WCF报错

一、WCF运行不起来api

System.ServiceModel.EndpointNotFoundException:“没有终结点在侦听能够接受消息的浏览器

 "ExceptionMessage": "没有终结点在侦听能够接受消息的 http://localhost.dev.xxx.com/Services/yyyService.svc。这一般是因为不正确的地址或者 SOAP 操做致使的。若是存在此状况,请参见 InnerException 以了解详细信息。","ExceptionType": "System.ServiceModel.EndpointNotFoundException",

多是 wcf服务没启动?

从IIS_Express中打开wcf站点,看是否有报错,

可能错误:未能加载配置文件;web.Config中wcf路径配置有误

路径错误,看是否须要修改.vs\config\applicationhost.config 中的虚拟路径  <virtualDirectory path="/Service" physicalPath="D:\sources.git\xxx\yyy" />

配置文件拷贝后,WCF运行起来。

二、调试不进断点

 调试选项里面的 “仅个人代码”,取消选中

 

 

三、没法自动进入并单步执行服务器。调试器未能在服务器进程中中止

 

以上设置都配置好后,清理解决方案,从新生成。

 四、域名绑定问题

 

能够看到,restapi请求WCF时 没有成功。

在本地看到wcf是ok的。可是在restapi所在的服务器上请求wcf是不行的。因而看服务器上的host,发现没有绑定 wcf域名对应的ip。

4、DBContext报类型初始值设定项引起异常

查看配置文件,configSource节点

<appSettings configSource="VConfigs\Dev\appSettings.config">

    <add key="ClientSettingsProvider.ServiceUri" value=""/>

  </appSettings>

手动改成

<appSettings configSource="VConfigs\Dev\appSettings.config"/>

参考:http://www.it1352.com/21840.html

5、  Missing type map configuration or unsupported mapping

Missing type map configuration or unsupported mapping. Mapping types: Discount -> DiscountEntity Ferry.Data.Models.Discount ->Entity.DiscountEntity Destination path: List`1[0] Source value: Data.Models.Discount,錯誤源:

参考:http://www.cnblogs.com/dudu/p/5875579.html

从 GitHub 上签出 AutoMapper 的源代码一看 Mapper.Initialize() 的实现,恍然大悟。

public static void Initialize(Action<IMapperConfigurationExpression> config)

{

    Configuration = new MapperConfiguration(config);

    Instance = new Mapper(Configuration);

}

原来每次调用 Mapper.Initialize() 都会建立新的 Mapper 实例,也就是屡次调用 Mapper.Initialize() 只有最后一次生效。

更多参考:【.NET】AutoMapper学习记录

 

6、the current .NET SDK does not support targeting .NET Standard 2.0. Either target .NET Standard 1.6 or lower, or use a version of the .NET SDK that supports .NET Standard 2.0

经过这句英文一直觉得是 .net framework 2.0未安装。

安装之后引用不报错(没有黄色感叹号),编译的时候却仍是报错。

 找到缘由,原文地址

https://stackoverflow.com/questions/45732236/the-current-net-sdk-does-not-support-targeting-net-standard-2-0-error-in-visua

 安装 .net core 2.0能够解决。

vs重启后,出错的项目 属性。从新选择目标平台。

7、模板生成pdf时内容不够却分页了

可能的缘由是:底部某些 标签(eg table)的元素太多致使,能够将太多元素标签的标签改造下。

 

 

8、初始化异常或内存不足

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

日志记录的详细信息:

System.TypeInitializationException: The type initializer for 'Ferry.Data.Models.FerryDBContext' threw an exception.

---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Utilities.TypeExtensions' threw an exception.

---> System.TypeInitializationException: The type initializer for 'System.Data.Entity.Core.Metadata.Edm.MetadataItem' threw an exception.

---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

咋一看是数据库(或者EF链接)初始化的问题。

若期间没有动过服务器或者DB,,则大体能够认为是服务器问题,能够重启服务,只重启出问题的应用程序池

 

9、https网站中样式资源没起做用

F12 看到js报错:Mixed Content: The page at 'https://xxx.com//app/#booking/search'

was loaded over HTTPS, but requested an insecure stylesheet 'http://xxx.com/Site/Styles/offline/main.css'.

This request has been blocked; the content must be served over HTTPS.

 

http://xxx.com/Site/Styles/offline/main.css这个资源(位于index.html中的<head>标签中)被阻塞了,

缘由:在https网站中,载入http网站的资源(网页、图片等),会被浏览器阻拦。HTTPS 是 HTTP over Secure Socket Layer,以安全为目标的 HTTP 通道,在 HTTPS 承载的页面上不容许出现 http 请求

正确应该是https://xxxx.com/Site/Styles/offline/main.css

 

10、未能加载文件或程序集

打开WCF时:未能加载文件或程序集“MongoDB.Bson, Version=2.2.3.3, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项。系统找不到指定的文件。

找到相应的目录:D:\sources.git\xxx\DEV\yyy.Offline.Service.Site\bin

看它里面是否有MongoDB.Bson程序集,没有的话copy一份进去。

11、分析器错误信息: 未能加载类型“xxxx.Global”

解决方法: 删除此项目下bin里面的全部dll,清理 从新生成。

12、VS中修改代码,再断点调试,发现命中的仍是修改前的代码

解决方法: 清理解决方案,再从新生成。

十3、LINQ to Entities 不识别方法“System.DateTime ToDateTime(System.String)”,所以该方法没法转换为存储表达式

 

由于LINQ语句最后都是要转为sql语句来执行的,当它转换后,发现sql语句中要执行的方法“XX”,并非一个在数据库中的存储过程函数,也没法进行转换为存储表达式。

即EF不支持复杂类型(如实体)的直接检索,只能用简单类型(string、int、guid等)

相似异常:LINQ to Entity 不识别方法“System.String ToString()”,所以该方法没法转换为存储表达式

最近在项目中遇到需求说,要模糊查询。因而有 

var query = store.Repository.Set<EFHotelOrder>().Where(p => p.OrderType == (byte)OrderType.Expert);
if (request != null)
{
if (request.OrderID != null)
{
query = query.Where(i => i.OrderID.ToString().Contains(request.OrderID.ToString()));
}
if (request.CityName != null)
{
query = query.Where(i => i.CityName.Contains(request.CityName));
}
View Code

因为orderId被设计为了int型,故用了toString()。因此报了上面的错误。

参考:LINQ to Entities 不识别方法“System.String ToXX()”,所以该方法没法转换为存储表达式

LINQ to Entity 不识别方法“System.String ToString()”,所以该方法没法转换为存储表达式

而此处遇到的是int型的模糊匹配问题,不适用,后来在网上发现:EF中 int没有模糊查询的概念;通常模糊查询都是针对字符串

 

十4、你的xxx.mdf 的版本为 782,没法打开,此服务器支持 655 版及更低版本,不支持降级路径

  现象:在vs2015中直接添加数据库和表,

  查找资料:782是sql server 2014的内部版本号(是vs2015自带的)、655是sql server2008(本机安装的数据库版本)

  缘由:你的mdf数据库文件是12.00.2000版本,而你的SQLEXPRESS倒是2008

(SQL Server Express 是由Microsoft所开发的SQL Server的其中一个版本,SQL Server Express 有 2005 、 2008 与 2008 R2 、2012 R0和最新的 2014五个版本)

      

查看数据库的版本,SSMS版本

 你调用的数据库文件版本过高,当前的数据库不支持,你只能将调用的数据库版本下降

解决:在本机只安装了sql server2008的状况下,数据库也要用管理工具建立的数据库,不能用vs2015上直接建立的

十5、基础链接已经关闭: 未能为 SSL/TLS 安全通道创建信任关系

  当咱们有时用代码编写post/Get请求url远程地址会报“基础链接已经关闭: 未能为 SSL/TLS 安全通道创建信任关系。 ---> System.Security.Authentication.AuthenticationException: 根据验证过程,远程证书无效

”这个异常,是由于远程url使用的域名 没有购买证书,因此用如下方式来解决:

在create url以前 设定“获取或设置用于验证服务器证书的回调”永远为true 便可,具体以下

请求必定须要:

ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

private static bool RemoteCertificateValidate(object sender, X509Certificate cert,X509Chain chain, SslPolicyErrors error)
        {
            //为了经过证书验证,老是返回true
            return true;
        }

或者

 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
 ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true;


十6、Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List

  没法将Newtonsoft.Json.Linq.JArray隐式转换为List<T> 

如今webapi通常使用json,

eg: data (Array[CollectionListItemExtend], optional):  返回data。。类型为JArry,那直接用List<>去接收,就会报上面的错误。

 在后台接口获取参数时,咱们可使用dynamic,如:

dynamic jArray = HttpHelper<string, RestAPIGetAccount<object>>.GetDataBy=API(url).Result;
            //JArray jArray = new JArray();
            //jArray.ToObject()
            if (jArray != null && jArray.head != null && jArray.head.code == 0)
            {
                List<AccAPI.CollectionListItemExtend> temp = jArray.data.ToObject(typeof(List<AccAPI.CollectionListItem>));
                if (temp != null && temp.Count > 0)
                {
                    string str = temp.ToJSON();
                    System.Console.ReadLine();
                }
            }

 public static async Task<RestAPIGetAccount<object>> GetDataBy(string url)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3;
            ServicePointManager.ServerCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true;

            var rs = new RestAPIGetAccount<object>() { head = new Entity.API.OfflineResponseHeader() };
            using (HttpClient client = GetHttpClient(url, 100))
            {
                try
                {
                    var httpResponseMessage = client.GetAsync(url).Result;
                    if (!httpResponseMessage.IsSuccessStatusCode)
                    {
                        var xmlResult = httpResponseMessage.Content.ReadAsStringAsync().Result;
                        rs.head.code = 500;
                        rs.head.message = "http请求失败";
                    }
                    else
                    {
                        var result = httpResponseMessage.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrWhiteSpace(result))
                        {
                            rs = result.FromJSON<RestAPIGetAccount<object>>();
                        }
                    }
                }
                catch (AggregateException ae)
                {
                    var exceptions = ae.InnerExceptions.ToList();
                    rs.head.message = string.Join(",", exceptions.Select(p => p.ToString()).ToArray());
                    rs.head.code = 500;
                    HotelHelper.WriteErrorLog(LogSourceType.Common, $"Get数据", $"url:{url}{Environment.NewLine}rs:{rs.ToJSON()}{Environment.NewLine}message:{ae.ToString()}");
                }
                catch (Exception ex)
                {
                    rs.head.message = ex.ToString();
                    rs.head.code = 500;
                    HotelHelper.WriteErrorLog(LogSourceType.Common, $"Get数据", $"url:{url}{Environment.NewLine}rs:{rs.ToJSON()}{Environment.NewLine}message:{ex.ToString()}");
                }
            }
            return rs;
        }



public class RestAPIGetAccount<T>
    {
        /// <summary>
        /// 返回data
        /// </summary>
        public T data { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public OfflineResponseHeader head { get; set; }
    }
    public class OfflineResponseHeader
    {
        /// <summary>
        ///   0-success, (客户端错误400-499) 401未登陆, 403没访问权限, (异常500-599) 500-error, 
        /// </summary>
        public int code { get; set; }
        /// <summary>
        /// 錯誤信息
        /// </summary>
        public string message { get; set; }
    }
View Code

实际上是 Newtonsoft.Json.Linq.JArry.ToObject()

 更多参考:Newtonsoft.Json.Linq.JArray转换为List    Convert JSON to a Type

 

十7、CS0656 C# 缺乏编译器要求的成员“Microsoft.CSharp.RuntimeBinder.Binder.Convert”

  在使用 dynamic 时生成失败,遇到这样一个错。

解决方法:在项目中添加对 "Micorsoft.CSharp.dll" 的引用

十8、 SqlDateTime 溢出,必须介于 1/1/1753 12:00:00 AM 和 12/31/9999 11:59:59 PM之间

  缘由:.NET中  DateTime最小值为: 0001-1-1 0:00:00

        数据库中DateTime最小值为: 1753-1-1 0:00:00,

很明显:.NET中的最小值超出了数据库时间类型的最小值,致使数据溢出的错误。(二者的最大值都是同样滴)

出现这种问题多半是由于插入或者更新数据库时,datetime字段值为空默认插入0001年01月01日形成datetime类型溢出

 传给数据库表的时间类型值是null值。这里的null指的是程序代码中的null,多数出现这种状况的场景是:在程序里面定义了一个时间类型的变量,没有给赋值,就传给数据库,这时这个变量的值默认是赋成了01年01月01日;因为数据库中DateTime类型字段,最小值是1/1/1753 12:00:00,而.NET Framework中,DateTime类型,最小值是1/1/0001 0:00:00,显然,超出了sql的值的最小值范围,致使数据溢出错误。

  解决方法: 

方法一、使用System.Data.SqlTypes.SqlDateTime.MinValue替代System.DateTime类型,这样SqlDateTime的MinValue和Sql中DateTime的范围吻合,就不会再出现以上的错误了。

方法二、DateTime为空或最小时,给其赋一个SqlDateTime最小值或者特定值

if (modelberthStatus.TIMEIN == null || modelberthStatus.TIMEIN == DateTime.MinValue)
       {
        modelberthStatus.TIMEIN = SqlDateTime.MinValue.Value;
        }
//或者:  modelberthStatus.TIMEIN = new DateTime(1900,1,1);