开发者

c# WCF REST strongly typed WebGet object for parameters and validation

开发者 https://www.devze.com 2023-04-01 06:28 出处:网络
Can you do the below in WCF 4.0 Rest like you can in ASP.NET MVC? In ASP.NET MVC I can create a strongly typed object commonly known as a ViewModel to handle error validation.

Can you do the below in WCF 4.0 Rest like you can in ASP.NET MVC?

In ASP.NET MVC I can create a strongly typed object commonly known as a ViewModel to handle error validation.

Instead of the following:

public ActionResult SomeAction(string firstname, string lastname, string address, int phone)

I could have the following:

public ActionResult SomeAction(UserObject obj)

Where UserObject is defined as:

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; }
}

What I am basically wanting to do is create the parameters in a strongly typed object and have my error messages there. I could then format the error message as xml and return it to the user.

So in WCF REST. Instead of My method looking like:

[WebGet]
public IEnumerable<ObjectResult> SomeAction(string firstname, string lastname, string address, int phone)

I w开发者_开发问答ant the following:

[WebGet]
public IEnumerable<ObjectResult> SomeAction(UserObject obj)

Is this possible in WCF REST 4.0?


Default WCF is not able to do that. You must create custom behavior with custom implementation of IDispatchMessageFormatter to collect parameters from query string and build the object. Here is an example how to build such behavior and formatter. It would be like if you have to write custom model binder for each custom ViewModel in ASP.NET MVC.

Btw. there is also no build in logic which would simply allow you to call validation (like Model.IsValid in MVC). You will need to use infrastructure classes used with data annotations manually (System.ComponentModel.DataAnnotations.Validator).

0

精彩评论

暂无评论...
验证码 换一张
取 消