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

与世无争的帅哥 提交于 2019-12-12 18:34:01

问题


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  }
}

回答1:


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);



回答2:


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()
{
    ... 
}


来源:https://stackoverflow.com/questions/7406891/how-to-call-static-method-from-asp-net-mvc-controller-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!