我有一些类,如 CustomerModel
或 CustomerDetailsModel
,它们继承自 ModelBase
。
我也不想为每个模型类型引入子类。
在一种情况下有一个 post 方法 foreach。
所以我可以手动创建多个路由来调用一个看起来像的方法
Handle<T>(T model) where T : ModelBase
它们仅在调用路径上有所不同。例如:
baseurl/api/customer => CustomerModel
baseurl/api/customerdetails => CustomerDetailsModel
我想实现一个通用的 web api 方法,例如
[HttpPost]
void Post<T>(T model) where T : ModelBase
如果我只是创建一个通用方法,我会得到一个异常,它告诉我 Web API 方法不能有通用方法。但前段时间我看到一个使用 web api v1 的实现使用某种自定义查找机制来处理这个问题。但我再也想不通了。
作为解决方法,我创建了一个 callwrapper,它确定类型并调用一个内部泛型方法,但这感觉很丑陋
public async Task<IHttpActionResult> Post(string id, string moduleType)
{
await AsyncGenericCallWrapper(moduleType);
...
要是有上面提到的通用 Controller r就好了。
private async Task AsyncGenericCallWrapper(string moduleType)
{
Type type = GetModuleType(moduleType);
var content = await Request.Content.ReadAsStringAsync();
var instance = JsonConvert.DeserializeObject(content, type);
MethodInfo method = this.GetType().GetMethod("InternalGenericMethod", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo generic = method.MakeGenericMethod(type);
var result = generic.Invoke(this, new object[] { instance }) as Task;
await result;
}
我可以想象有一个自定义属性来映射类型
[GenericRoute("/customer", typeof(CustomerModel)]
[GenericRoute("/customerDetail", typeof(CustomerDetailModel)]
void Post<T>(T model) where T : ModelBase
有了这个我可以为每个属性创建路由,但现在仍然调用该方法,因为它是通用的,我也不知道如何干扰反序列化机制
谁能告诉我如何实现该 GenericWebAPIMethod?
最佳答案
这种方法的问题是 Web API 不知道如何反序列化对象。
您可以创建一个通用 Controller ,而不是拥有一个通用方法。
假设您的模型是这样的:
public abstract class ModelBase{ }
public class CustomerModel : ModelBase {}
public class CustomerDetailsModel: ModelBase { }
您可以编写一个通用 Controller 来处理从 ModelBase 继承的类:
public class ModelBaseController<T> : ApiController where T : ModelBase
{
[HttpPost]
public void Post(T model)
{
...
}
}
public class CustomerModelController : ModelBaseController<CustomerModel>
{
}
public class CustomerDetailsModelController : ModelBaseController<CustomerDetailsModel>
{
}
关于c# - 通用 Web Api 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29398241/