dotnet core出2.0了。把一些現有代碼試着做了下遷移,出乎意料的順利。
這裏分享一些有用的nuget包,和有用的代碼:
nuget包名 | 引用原因 | 其他 |
Microsoft.AspNetCore.Http | Http處理 | HttpContext.Current方法需要替代方案 |
Microsoft.AspNetCore.Mvc.Core | Http處理 | |
Microsoft.Extensions.Caching.Memory | MemoryCache | 需要補充Contains方法 |
Microsoft.Extensions.Configuration | 配置文件 | |
Newtonsoft.Json | Json | |
StackExchange.Redis | Redis | |
System.Configuration.ConfigurationManager | AppSettings和ConnectionString | app.config需要自己手動增加 |
System.Data.SqlClient | SQLConnection | 注意從linux訪問的時候,sqlserver需要2008sp4以上版本。 |
System.Net.Http | Http處理 | |
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();
}