您能否像在 ASP.NET MVC 中一样在 WCF 4.0 Rest 中执行以下操作?
在 ASP.NET MVC 中,我可以创建一个通常称为 ViewModel 的强类型对象来处理错误验证。
代替以下内容:
public ActionResult SomeAction(string firstname, string lastname, string address, int phone)
我可以有以下内容:
public ActionResult SomeAction(UserObject obj)
其中 UserObject 定义为:
public class UserObject
{
[Required(ErrorMessage = "firstname is a required paramater")]
public string firstname { get; set; }
[StringLength(50, ErrorMessage = "lastname is too long")]
public string lastname { get; set; }
[StringLength(160)]
public string address { get; set; }
public int phone { get; set; }
}
我基本上想做的是在强类型对象中创建参数,并在那里显示我的错误消息。然后我可以将错误消息格式化为 xml 并将其返回给用户。
所以在 WCF REST 中。而不是我的方法看起来像:
[WebGet]
public IEnumerable<ObjectResult> SomeAction(string firstname, string lastname, string address, int phone)
我想要以下内容:
[WebGet]
public IEnumerable<ObjectResult> SomeAction(UserObject obj)
这在 WCF REST 4.0 中可能吗?
最佳答案
默认 WCF 无法做到这一点。您必须使用 IDispatchMessageFormatter
的自定义实现创建自定义行为,以从查询字符串中收集参数并构建对象。 Here is an example 如何构建此类行为和格式化程序。这就像您必须为 ASP.NET MVC 中的每个自定义 ViewModel 编写自定义模型联编程序一样。
顺便说一句。也没有内置逻辑可以让您调用验证(如 MVC 中的 Model.IsValid
)。您将需要手动使用与数据注释一起使用的基础结构类 (System.ComponentModel.DataAnnotations.Validator
)。
关于c# WCF REST 用于参数和验证的强类型 WebGet 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7259727/