API 调用
我正在使用以下消息正文进行 REST API 调用:
{"Method":{"Token":"0","Value":"0"}}
400 响应
我从 api 收到 400 Bad Request 响应,其正文如下:
{"Message":"The request is invalid.","ModelState":{"request.Method.Token":["Could not create an instance of type Namespace.ActionMethod. Type is an interface or abstract class and cannot be instantiated. Path 'ActionMethod.Token'."]}}
代码信息
接收 api 调用的方法如下所示:
public MethodResponse MakeMethodCall([Required] [FromBody] MethodRequest request)
MethodRequest
有一个 Method
属性,它是一个抽象类型。
public class MethodRequest
{
public ActionMethod Method { get; set; }
}
public abstract class ActionMethod
{
public string Token { get; set; }
}
public class FirstMethod : ActionMethod
{
public string Value { get; set; }
}
问题
如何调用 REST API 并让它识别出 Method
的类型是 FirstMethod
,而不是尝试实例化抽象类型 ActionMethod
?
请注意,我将来需要更多的 ActionMethod
实现(即 SecondMethod
),因此解决方案需要包含可扩展的 ActionMethod
(界面也很好)。
编辑
包含一个 enum
来识别 API 调用针对 ActionMethod
的哪个实现也是合理的。
我当前使用的解决方案具有 ActionMethodType
枚举以及 FirstMethod
和 SecondMethod
字段。我根据 ActionMethodType
的值检查这些字段。这可行,但我希望有一个 [Required]
字段,我可以将 ActionMethod
的任何实现传递到其中。
最佳答案
无法完成。框架如何知道为此参数实例化 FirstMethod?如果您的 ActionMethod 的另一个子类也具有 Value 属性怎么办?现在,框架自己解决问题就更加模糊了。您可以做很多工作,创建一个自定义格式化程序( http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx ),但最终只拥有一个包含客户端可以发送的所有可能属性的类会更容易,或者拥有单独的 API 端点供客户端使用不同的调用具体类型作为参数。
关于c# - 如何在 C# 中定义带有抽象参数的 REST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25295035/