Last active
December 11, 2015 19:49
-
-
Save JohannesHoppe/4651234 to your computer and use it in GitHub Desktop.
Manipulates the default behavior of Model Binding to initialize strings to String.Empty. (as in ASP.NET MVC 1.0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Reflection; | |
using MySolution; | |
using PostSharp.Aspects; | |
using PostSharp.Extensibility; | |
[assembly: EmptyStringModelBindingAspect( | |
AttributeTargetTypes = @"regex:[^\.]*\.Controllers\..*Controller", | |
AttributeTargetTypeAttributes = MulticastAttributes.Public, | |
AttributeTargetElements = MulticastTargets.Method, | |
AttributeTargetMemberAttributes = MulticastAttributes.Public)] | |
namespace MySolution | |
{ | |
[Serializable] | |
public class EmptyStringModelBindingAspect : MethodInterceptionAspect | |
{ | |
public override void OnInvoke(MethodInterceptionArgs args) | |
{ | |
for (int i = 0; i < args.Arguments.Count; i++) | |
{ | |
FixString(args, i); | |
FixStringsInObjects(args.Arguments[i]); | |
} | |
args.Proceed(); | |
} | |
private static void FixString(MethodInterceptionArgs args, int i) | |
{ | |
if (args.Arguments[i] is string && | |
args.Arguments[i] == null) | |
{ | |
args.Arguments.SetArgument(i, string.Empty); | |
} | |
} | |
private static void FixStringsInObjects(object obj) | |
{ | |
if (obj == null) | |
{ | |
return; | |
} | |
Type type = obj.GetType(); | |
PropertyInfo[] properties = (from p in type.GetProperties() | |
where p.PropertyType == typeof(string) && | |
p.CanRead && | |
p.CanWrite && | |
p.GetValue(obj, null) == null | |
select p).ToArray(); | |
foreach (PropertyInfo item in properties) | |
{ | |
item.SetValue(obj, string.Empty, null); | |
} | |
} | |
public override bool CompileTimeValidate(MethodBase method) | |
{ | |
return !(method.Name.StartsWith("get_") || method.Name.StartsWith("set_")); | |
} | |
} | |
} |
I solved it like this:
private static void FixString(MethodInterceptionArgs args, int i)
{
ParameterInfo[] paramInfo = args.Method.GetParameters();
if (paramInfo[i].ParameterType == typeof(string) && args.Arguments[i] == null)
{
args.Arguments.SetArgument(i, string.Empty);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how could you tell the type of an argument if its value is null? For me (using MVC 4) "if(args.Arguments[i] is string)" always returns false