dotnetcore遷移方法初步


dotnet core出2.0了。把一些現有代碼試着做了下遷移,出乎意料的順利。


這裏分享一些有用的nuget包,和有用的代碼:

nuget包名引用原因其他
Microsoft.AspNetCore.HttpHttp處理HttpContext.Current方法需要替代方案
Microsoft.AspNetCore.Mvc.CoreHttp處理 
Microsoft.Extensions.Caching.MemoryMemoryCache需要補充Contains方法
Microsoft.Extensions.Configuration配置文件 
Newtonsoft.JsonJson 
StackExchange.RedisRedis 
System.Configuration.ConfigurationManagerAppSettings和ConnectionStringapp.config需要自己手動增加
System.Data.SqlClientSQLConnection注意從linux訪問的時候,sqlserver需要2008sp4以上版本。
System.Net.HttpHttp處理 
Microsoft.PinYinConverter中文處理這個nuget包比較特別,是4.6.1的,但是dotnetcore聲稱可以直接引用。需要測試。
Magick.NET-Q8-AnyCPU圖像處理Bitmap都要改用ImageMagick.MagickImage。
不能直接替換。座標和字體需要注意。
   
   


再貼點有用的代碼:

//代替HttpContext.Current
public partial class MyHttpContext
{
    public static IServiceProvider ServiceProvider;

    /// <summary>
    /// 注意多線程下這個方法可能不準確
    /// </summary>
    public static Microsoft.AspNetCore.Http.HttpContext Current
    {
        get
        {
            object factory = ServiceProvider.GetService(
                typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
            Microsoft.AspNetCore.Http.HttpContext context = 
                ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
            return context;
        }
    }

}

//爲MemoryCache補上Contains方法
public static class DefaultExtentions
{
    public static bool Contains(this MemoryCache mc, string key)
    {
        if (mc.Get(key) == null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

//dotnetcore目前沒有自帶hex處理
public static byte[] HexStringToBytes(string hex)
{
    int NumberChars = hex.Length;
    byte[] bytes = new byte[NumberChars / 2];
    for (int i = 0; i < NumberChars; i += 2)
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    return bytes;
}

//
public static string BytesToHexString(byte[] ba)
{
    StringBuilder hex = new StringBuilder(ba.Length * 2);
    foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);
    return hex.ToString();
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章