在 .NET5 之前,我们通过以下代码序列化/反序列化字节/对象:
private static byte[] StructToBytes<T>(T t)
{
using (var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, t);
return ms.ToArray();
}
}
private static T BytesToStruct<T>(byte[] bytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(bytes, 0, bytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = binForm.Deserialize(memStream);
return (T)obj;
}
}
Run Code Online (Sandbox Code Playgroud)
但出于安全原因,BinaryFormatter 将被删除:
https://docs.microsoft.com/zh-cn/dotnet/standard/serialization/binaryformatter-security-guide
那么有没有一些简单但高性能的方法来代替 BinaryFormatter 呢?
适用于:
失败:
测试应用程序:Mono MVC5 Web API2测试用例
测试程序:
a)服务器将在失败时返回500错误
b)console.log成功发布arg
Error: {
"Message": "An error has occurred.",
"ExceptionMessage": "Method 'HttpRequestBase.GetBufferedInputStream' not found.",
"ExceptionType": "System.MissingMethodException",
"StackTrace": " at System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent.get_StreamContent () [0x00008] in :0
at System.Web.Http.WebHost.HttpControllerHandler+LazyStreamContent.CreateContentReadStreamAsync () [0x00000] in :0
at System.Net.Http.HttpContent+c__async2.MoveNext () [0x00095] in /private/tmp/source-mono-mac-4.0.0-branch-c5sr4/bockbuild-mono-4.0.0-branch/profiles/mono-mac-xamarin/build-root/mono-4.0.4/mcs/class/System.Net.Http/System.Net.Http/HttpContent.cs:159
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000b] in /private/tmp/source-mono-mac-4.0.0-branch-c5sr4/bockbuild-mono-4.0.0-branch/profiles/mono-mac-xamarin/build-root/mono-4.0.4/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) …Run Code Online (Sandbox Code Playgroud)我使用的是EF Core 3.1 + MySQL,并使用这种方法进行查询:
IQueryable<ApplicationUser> customers = from u in _context.Users where (u.Customer != null && u.IsActive) select u;
if (!String.IsNullOrEmpty(searchString))
{
customers = customers.Where(s => s.Email.Contains(searchString));
}
Run Code Online (Sandbox Code Playgroud)
我升级为使用 EF.Function.Like 以获得更好的性能:
if (!String.IsNullOrEmpty(searchString))
{
customers = customers.Where(x => EF.Functions.Like(x.Email, $"%{searchString}%"));
}
Run Code Online (Sandbox Code Playgroud)
但它是区分大小写的,如何使其不区分大小写呢?