C#使用泛型调用作为MVC ActionResult

3

我有一个在ASP.NET MVC4中使用通用方法的操作:

public ActionResult Test1()
{
    return Generic<TestClass>();
}

public ActionResult Test2(string className)
{
    MethodInfo method = typeof(ConfigController).GetMethod("Generic");
    MethodInfo generic = method.MakeGenericMethod(Type.GetType(className));
    generic.Invoke(this, null);
    return null; // Generic<TestClass>();
}

public ActionResult Generic<T>() where T : new()
{
    DatabaseUtil db = new DatabaseUtil();
    ViewBag.ClassName = typeof(T).AssemblyQualifiedName;
    return View("~/Views/Config/GenericConfig.cshtml", db.SelectAll<T>());
}

Test1()的工作完全符合预期,它将TestClass传递给通用方法,并使用相应对象的模型返回视图。

我想进一步发展并只传递类名作为字符串,以便我不需要为我想要使用的每种类型都编写特定的操作。

Test2()的工作已经进行到返回视图的地步。我知道invoke正在工作,因为我在Generic<T>中以正确的类类型命中了断点,但是Test2()返回的仍然是传回浏览器的内容。

我如何将返回委托给通用调用的ActionResult方法?


2
我不明白,为什么你不直接返回(ActionResult)generic.Invoke(null, null);?顺便说一下:对于这样的代码要非常小心,因为它可能是一个巨大的安全漏洞(调用者可以实例化任何类型,潜在地也可能在其构造函数中执行昂贵或有害的操作)。 - Adriano Repetti
1
@Paul,为什么你只传递一个可能是类名的代码,然后存储一个代码到类型的字典,并以这种方式实例化它。这样做还可以消除安全漏洞。 - johnny 5
@AdrianoRepetti 还是很新于泛型,刚在发帖后自己找到了解决方案。 - Paul
1
@johnny5 好主意,我一定会实现的。这是一个内部应用程序,所以安全性不是一个巨大的问题,但始终是一个良好的考虑因素。 - Paul
1个回答

3

它就在我面前(我对反射还很陌生):

public ActionResult Test(string className)
{
    MethodInfo method = typeof(ConfigController).GetMethod("Generic");
    MethodInfo generic = method.MakeGenericMethod(Type.GetType(className));
    ActionResult ret = (ActionResult)generic.Invoke(this, null);
    return ret; 
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接