开发者

extension method for a method C#

Is there a way to have extension method on the method? Example for this would be method that takes some user object a开发者_开发技巧s parameter and you need to do security check if that user can use that method at the very beginning of the method. Can the method have extension method like "check can this user use me" and return bool.

Thanks.


You can use Aspect Oriented Programming (AOP) to implement cross-cutting security checks in your code.

In .NET you have a choice of several AOP frameworks, for example:

  • Spring.NET
  • PostSharp

In particular the PostSharp documentation has some nice examples on how to implement security using AOP.


You can't add extension method for a method with C#.

But you could use Aspect Oriented Programming (AOP) to do what you want, using PostSharp or Spring.NET for example.

  • Example of securing methods with PostSharp

    public class BusinessDivision : BusinessObject
    {
        [SecuredOperation("Manager")]
        public void EnlistEmployee(Employee employee)
        {
            // Details omitted.
        }
    }
    


I am not quite sure what you are looking for but this smells like declarative security to me.

Take a look at: http://msdn.microsoft.com/en-us/library/kaacwy28.aspx


I'm not sure if I understand your question well. However, what about this:

public static void EnsureUserHasAccess(this object obj)
{
    // check permissions, possibly depending on `obj`'s actual type
}

public static void DoSomething(this MyClass obj)
{
    // permissions check
    obj.EnsureUserHasAccess();

    // do something about `obj`
    …
}

public static void DoSomethingElse(this MyDifferentClass obj)
{
    // permissions check
    obj.EnsureUserHasAccess();

    // do something about `obj`
    …
}


Extension methods in C# are not extensions of methods (not sure I understand what that means), but methods that extend objects/classes.

If you want to inject the kind of checks you are describing into your code, you can look into PostSharp and AOP.


You can go with madgnome's answer, which is based on aspect programming (glad to see that somebody used that in .net) or you can use attributes and paste some code in every method that should be guarded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜