开发者

How to call static method from ASP.NET MVC controller in C#

GetMethod does not find public static method if called from ASP .NET MVC controller. (From console application it work OK).

To solve this dummy SaveEntityGenericWrapper method is used.

How to remove SaveEntityGenericWrapper from code ?

Why GetMethod("SaveEntityGeneric") returns null but GetMethod("SaveEntityGenericWrapper") works if called from ASP .NET MVC 2 controller ?

How to make SaveEntityGeneric private if partial trust is used in MVC2 ?

public class EntityBase() {

    public void SaveEntity(EntityBase original)
    { 
        var method = GetType().GetMethod("SaveEntityGenericWrapper");
        // why this line returns null if called from ASP .NET MVC 2 controller:
        // method = GetType().GetMethod("SaveEntityGeneric");
        var gm = method.MakeGenericMethod(GetType());
        gm.Invoke(this, new object[] { original, this });
    }

    // Dummy wrapper reqired for mvc reflection call only. 
    // How to remove it?
    public List<IList> SaveEntityGenericWrapper<TEntity>(TEntity original, TEntity modified)
        where TEntity : EntityBase, new()
    {
        return SaveEntityGeneric<TEntity>(original, modified);
    }

    public static List<IList> SaveEntityGeneric<TEntity>(TEntity original, TEntity modified)
                where TEntity : EntityBase, new()
    { ... actual work is performed here  开发者_StackOverflow社区}
}


You need to specify BindingFlags in the GetMethod call so that static methods are retured (I think that by default only public instance methods are returned)

 var method = GetType().GetMethod("SaveEntityGenericWrapper",
                                  BindingFlags.Static|BindingFlags.Public);


Simply do not make problems with private, trying to solve bravely more complex problems.

See your previous post, how simple it was.

At least, use

internal static List<IList> SaveEntityGeneric<TEntity>(TEntity original, TEntity modified)
                where TEntity : EntityBase, new()
{
    ... 
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜