我有几个派生类B
和C
继承自同一基类A
:
public class A {}
public class B : A {}
public class C : A {}
我需要创建一个HTTP POST API方法来使用每个具体的类。有一个接受基类的方法或为每个派生类创建单独的方法更好吗?
[Route("send/Base")]
[HttpPost]
public IHttpActionResult SendPricingLetter(A model)
{
// do some type checking and perform logic
}
我正在使用工厂进行类型检查并为每个类设置适当的字段,看起来它很快就会变得无法管理。
或者
[Route("send/ConcreteB")]
[HttpPost]
public IHttpActionResult SendSomeOther(B model)
{
// No type checking required and perform logic
}
[Route("send/ConcreteC")]
[HttpPost]
public IHttpActionResult SendStuff(C model)
{
// No type checking required and perform logic
}
答案 0 :(得分:1)
即使您发布SendPricingLetter
或A
,您的方法B
也会始终收到C
的实例。这与反序列化的工作方式有关。你的方法"做一些类型检查"将无法工作,因为您将始终必须处理A
类型的对象。没有迹象表明它们是来自A
,B
还是C
。
我不确定你的要求是什么;但是,在Web API方法中,您考虑的是数据模型,而不是面向对象的继承原则。我个人喜欢遵循REST原则,这些原则使您能够以面向域的方式进行更多思考。
检查您的班级建模是否正确。如果是这样,如果您真的需要将这些不同的对象传输到您的API,那么您要么提供三种不同的方法,一种用于A
,一种用于B
,一种用于C
, - 或者 - 您只需拨打一个电话,就可以相应地处理A
,B
和C
,例如:
public class MyRequestModel
{
public DomainModelType Type { get; set; }
public A ToDomainObject()
{
switch (Type)
{
case DomainModelType.A:
return new A();
case DomainModelType.B:
return new B();
case DomainModelType.C:
return new C();
default:
throw new InvalidOperationException();
}
}
}
[Route("Stuff")]
[HttpPost]
public IHttpActionResult Stuff(MyRequestModel requestModel)
{
var myOriginalObject = requestModel.ToDomainObject();
// do some type checking and perform logic
}
我个人总是会使用明确的API调用(在您的情况下为三个),除非我有一个有效的要求将它们保持在一起。