我可以使用postharp修改输入参数吗?

时间:2018-12-14 17:39:23

标签: c# postsharp

我想使用postsharp创建一个属性,该属性将使用HTMLIncode输入参数。像这样:

public void Mymethod([HTMLEncode]string parm1,[HTMLEncode]string parm2){
    ....
}

我想选择性地将其放置在输入参数上。这可能吗?

1 个答案:

答案 0 :(得分:0)

可以使用MethodInterceptionAspect修改方法的输入参数。在您的特定情况下,您可以在HTMLEncodeAttribute类中实现IAspectProvider并在相应的声明方法上提供拦截方面。例如:

[AttributeUsage(AttributeTargets.Parameter)]
public class HTMLEncodeAttribute : Attribute, IAspectProvider
{
    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        ParameterInfo parameter = (ParameterInfo)targetElement;
        IAspectRepositoryService aspectRepositoryService = PostSharpEnvironment.CurrentProject.GetService<IAspectRepositoryService>();

        if (!aspectRepositoryService.HasAspect(parameter.Member, typeof(HTMLEncodeImplAspect)))
        {
            yield return new AspectInstance(parameter.Member, new HTMLEncodeImplAspect());
        }
    }
}

[PSerializable]
public class HTMLEncodeImplAspect : MethodInterceptionAspect
{
    private List<int> encodedParams;

    public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
    {
        this.encodedParams = new List<int>();
        ParameterInfo[] allParams = method.GetParameters();
        for (int i = 0; i < allParams.Length; i++)
        {
            if (allParams[i].GetCustomAttribute(typeof(HTMLEncodeAttribute)) != null)
            {
                this.encodedParams.Add(i);
            }
        }
    }

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        foreach (int p in this.encodedParams)
        {
            args.Arguments.SetArgument(p, "encoded value");
        }
        args.Proceed();
    }
}