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();
}