你可以在控制器中使用泛型方法吗? [英] Can you use generic methods in a controller?

查看:1059
本文介绍了你可以在控制器中使用泛型方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在控制器中使用通用方法?我在谈论这样的事情:

  [HttpPost] 
public void DoSomething< T>([FromBody] SomeGenericClass< T> someGenericObject);
{
SomePrivateMethod< T>(someGenericObject);
}

我已经尝试了上面的(虽然名称不同)在请求正文中将 Api /< controllername> / DoSomething someGenericObject< T> 没有工作(即它没有到达控制器)。

我猜Web API路由不能解决泛型方法,因为它们可能导致底下不同类型的不同方法。但这正是我想的。



那么,在控制器中是否可以使用泛型方法?




  • 如果是,如何?

  • 如果不是,为什么?


  • 解决方案

    Sort of是这里的答案。对于泛型,您最终必须定义 ,否则这只是理论上的。 Web API或MVC如何将请求中的数据(只是QueryString GET或FormData POST键 - 值对)路由到泛型并自动推断出预期类型?这不可以。你可以做的是在控制器上创建一个私有的泛型方法,但是将控制器的Action方法解析为传递给私有泛型方法的具体类型。



    您也可以查看此SO回答作为替代方案,基于约定的方法。它应该对你的工作很好,假设你将通用控制器的具体类型指定为URL,QueryString或FormData的一部分。


    Is it possible to have a generic method in a controller? I'm talking about something like this:

        [HttpPost]
        public void DoSomething<T>([FromBody] SomeGenericClass<T> someGenericObject)
        {
            SomePrivateMethod<T>(someGenericObject);
        }
    

    I have actually tried the above (though with different names for everything) and posted to Api/<controllername>/DoSomething with the instance of someGenericObject<T> in the request body, and it didn't work (i.e. it didn't reach the controller).

    I'm guessing that Web API routing is not able to resolve generic methods since they may result in different methods for different types underneath. But that's just what I think.

    So, is it possible to have a generic method in a controller?

    • If yes, how?
    • If not, why?

    解决方案

    "Sort of" is the answer here. With generics, you must eventually define the underlying type somewhere and at some point or else it's all just theoretical. How would Web API or MVC route the data in your request (which is just QueryString GET or FormData POST key-value pairs) to a generic type and automatically infer the intended type? It cannot. What you could do is make a private generic method on the controller, but have the Action Methods of the controller resolve to concrete types which are passed to the private generic method.

    You could also take a look at this SO answer as an alternative, convention-based approach. It should work pretty well for you assuming that you are specifying the concrete type of your generic controller as part of the URL, QueryString, or FormData.

    这篇关于你可以在控制器中使用泛型方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆