# Heap_Inspection SecureString ###### tags: `.net core` `.net` `弱掃` `SecureString` [參考網址](https://rainmakerho.github.io/2021/07/14/Heap-Inspection-MVC-SecureString/) ``` [ModelBinder(BinderType = typeof(SecureStringModelBinder))] public class AccountViewModel { public string Account { get; set; } public SecureString Password { get; set; } //前端正常回傳字串給ModelBinder處理 } public static class SecureStringExtension { public static SecureString ToSecureString(this char[] self) { var secureString = new SecureString(); foreach (char c in self) { secureString.AppendChar(c); } return secureString; } public static SecureString ToSecureString(this string self) { var secureString = new SecureString(); char[] chars = self.ToCharArray(); foreach (char c in chars) { secureString.AppendChar(c); } return secureString; } public static string ToText(this SecureString self) { IntPtr bstr = Marshal.SecureStringToBSTR(self); try { return Marshal.PtrToStringBSTR(bstr); } finally { Marshal.FreeBSTR(bstr); } } } public class SecureStringModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var modelType = bindingContext.ModelMetadata.ModelType; var model = Activator.CreateInstance(modelType); foreach (var propInfo in modelType.GetProperties( BindingFlags.Public | BindingFlags.Instance)) { var propValue = bindingContext.ValueProvider.GetValue(propInfo.Name).FirstValue; if (propInfo.PropertyType == typeof(SecureString)) { propInfo.SetValue(model, propValue.ToSecureString(), null); } else { if (!string.IsNullOrEmpty(propValue)) { //set value by property type var converter = TypeDescriptor.GetConverter(propInfo.PropertyType); propInfo.SetValue(model, converter.ConvertFromString(propValue), null); } } } bindingContext.Model = model; bindingContext.Result = ModelBindingResult.Success(bindingContext.Model); return Task.CompletedTask; } } ```