【知識筆記】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);
相關文章
相關標籤/搜索