[英]How to pass instance of complex object via uri or http body without any params to asp.net web api controller?
I want to create instance of some type based on selected value, so I pass this type's name as a string via url using jquery.ajax() method to web api controller method, where I create instance of this type with reflection. 我想根据选定的值创建某种类型的实例,因此我使用jquery.ajax()方法将这种类型的名称作为字符串通过url传递给Web api控制器方法,在该方法中,我使用反射来创建这种类型的实例。
But I'm conserned about this approach. 但是我对此方法很了解。
I know that I can implement ModelBinding
with custom TypeConverter
or [FromUri]
attribute. 我知道我可以使用自定义TypeConverter
或[FromUri]
属性来实现ModelBinding
。 And pass some data to initialize object fields. 并传递一些数据来初始化对象字段。
The problem is that my type has default empty constructor and it doesn't need any fields to be initialized. 问题是我的类型具有默认的空构造函数,并且不需要初始化任何字段。
How can I pass instance of complex object via url or http body, without specifying any parameters? 如何在不指定任何参数的情况下通过url或http正文传递复杂对象的实例?
You are right you need to implement you own custom model binder, which will call 没错,您需要实现自己的自定义模型联编程序,该联编程序将调用
Activator.CreateInstance. Activator.CreateInstance。 Then you need to apply the MoldeBindingAttribute to your action. 然后,您需要将MoldeBindingAttribute应用于您的操作。 In the action itself you need to declare a parameter of type object(because you don't know the type at compilation time). 在动作本身中,您需要声明一个object类型的参数(因为在编译时您不知道类型)。 That is the only way to achive your requirements. 这是达到您的要求的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.