一些踩過的坑,踩過的坑
1)關於特性過濾器
這個我們經常用到,一般用在捕捉異常還有權限控制等方面,這個用著比較方便,但是這個確隱藏著一個坑,就是呢,特性過濾器會在被第一次訪問的時候創建一次,僅僅會被創建一次,然後就被aspnet緩存下來,之後就是取緩存了。
所以說如果我們要定義特性類的話,必須要注意一點就是裡面不能包含狀態可變的局部變量,因為會存在線程安全問題
2)關於nuget程序集版本
我們程序裡面用到nuget的地方有很多,但是有的時候我們會出現不同程序集引用的nuget包版本不一樣,但是程序編譯完成之後web目錄下只會有一個版本的dll,這樣如果是強名稱的包的話就會拋出版本異常,所以這種情況我建議是盡量保持所有程序集版本相同。
當然還有一個應急解決方案,就是webconfig下會有這麼個節點
![]()
這個節點的作用就是程序集重定向,做程序集版本檢查的時候對old版本的引用會被重定向到新版本
3)關於集合的線程安全
Dictionary<,>,List<>:
線程非安全:
添加刪除操作都會維護一個version字段,每次+1
然後生成的迭代器的時候會傳入version版本號,然後呢,迭代的時候會判斷迭代器的version是否和version相同,如果不同則拋出異常
所以說如果發生並發操作,一個線程正在查詢dic的時候另一個線程對這個dic做了修改則會拋出異常
ConcurrentDictionary
線程安全
采用了 volatile 來設置和取值
沒有維護version字段
4)關於Https
目前由於我們需要使用https,所以頁面也會針對請求內容來進行兼容,http的請求需要返回http後綴的靜態內容,https的要返回帶https後綴的靜態內容,所以我們就會想到通過請求方式來判斷,在程序中獲取用戶的請求方式,從而達到目的
但是上面的方式是有問題的,而且這個問題只有在生產環境草會被發現:
由於生產環境的證書是配置在nginx服務器上的,所以https只會到達nginx,nginx轉發到我們web服務器的時候依舊是http請求,所以這種方式在生產環境始終是http的
所以推薦的解決方案就是配置靜態地址的時候不要加上協議頭,src可以直接寫成"//res.rongzi.com....."這樣浏覽器就會根據具體的請求來識別使用哪種協議
5)關於HttpClient
目前我們項目裡面的代碼都習慣於使用using(HttpClient client = new HttpClient){}
但是這麼寫是有問題的:
1、就是HttpClient自己本身會維護一個連接池,所以說其實這個HttpClient只要實例化一個即可滿足所有要求
2、以上調用方法使用完成會調用client的DIspose方法來釋放這個池子,但是呢,這個池子的完全釋放需要4分鐘左右的時間,所以呢,這個會導致一個問題,就是這個如果4分鐘之內請求到達 一定程度就會耗盡套接字,從而拋出一個異常(主站曾經出現過這樣的問題)
具體文章鏈接:
http://www.infoq.com/cn/news/2016/09/HttpClient
所以針對這種情況我封裝了一個HttpHelper的類來處理請求:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Platform.Facilitys
{
public static class HttpHelper
{
static readonly HttpClient _client;
static HttpHelper()
{
_client = new HttpClient();
}
public static TOut PostSync<TIn, TOut>(ApiHost host, TIn postData)
where TIn : class
where TOut : class
{
var uri = new Uri(host.Domain);
var url = new Uri(uri, host.ApiName);
var response = _client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(postData),Encoding.UTF8,host.DataMimeType)).Result;
response.EnsureSuccessStatusCode();
return response.Content.DesObj<TOut>();
}
public static Task<TOut> PostAsync<TIn, TOut>(ApiHost host, TIn postData)
where TIn : class
where TOut : class
{
var uri = new Uri(host.Domain);
var url = new Uri(uri, host.ApiName);
return _client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, host.DataMimeType)).GetResult<TOut>();
}
public static Task<TOut> GetAsync<TOut>(ApiHost host)
where TOut : class
{
var uri = new Uri(host.Domain);
var url = new Uri(uri, host.ApiName);
return _client.GetAsync(url).GetResult<TOut>();
}
static Task<TOut> GetResult<TOut>(this Task<HttpResponseMessage> tsk)
where TOut : class
{
return tsk.ContinueWith(
res =>
{
return res
.Result
.EnsureSuccessStatusCode()
.Content
.DesObj<TOut>();
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
static TOut DesObj<TOut>(this HttpContent content)
where TOut : class
{
var strJson = content.ReadAsStringAsync().Result;
if (!string.IsNullOrWhiteSpace(strJson))
{
if (strJson.IndexOf("k__BackingField") > 0)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TOut));
using (var mStream = new MemoryStream(Encoding.Default.GetBytes(strJson)))
{
return ser.ReadObject(mStream) as TOut;
}
}
else
{
return JsonConvert.DeserializeObject<TOut>(strJson);
}
}
return default(TOut);
}
}
/// <summary>
/// WebApi配置
/// </summary>
public class ApiHost
{
#region
public ApiHost()
{
DataMimeType = "application/json";
}
public ApiHost(string domain, string apiName, string inputQueryString, string dataMimeType)
{
Domain = domain;
ApiName = apiName;
InputQueryString = inputQueryString;
DataMimeType = dataMimeType;
}
#endregion
#region
/// <summary>
/// 主域名(比如http://api.rongzi.com or http://127.0.0.1)
/// </summary>
public string Domain { get; set; }
/// <summary>
/// Api名稱(api/v1/studentinfotest)
/// </summary>
public string ApiName { get; set; }
/// <summary>
/// 傳入參數名稱
/// </summary>
public string InputQueryString { get; set; }
/// <summary>
/// 返回數據類型
/// </summary>
public string DataMimeType { get; set; }
/// <summary>
/// 重寫ToString()
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0}|{1}|{2}|{3}",
this.ApiName,
this.Domain,
this.DataMimeType,
this.InputQueryString);
}
#endregion
}
}
![HttpHelper.cs HttpHelper.cs]()
6)關於線程存儲
我們在開發的過程中,有時候在一個web生命周期內會需要從前到後傳遞一些對象之類的東西,這個時候可能會用到一個手段CallContext.SetData來設置數據,這個方法是將內容存放到線程中,所以只要在同一個線程中都可以取到這個內容,但是如果這個Action是異步的,async的,就會導致會有多個線程依次處理這個請求,這種情況往往是取不到之前設置的值的,這時候就可以使用CallContext.LogicSetData來設置值,這種方式設置的內容會被拷貝到新線程中