简体   繁体   中英

REST service how to pass JSON for parameters

I have created a WCF REST API:

[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,  
           BodyStyle = WebMessageBodyStyle.WrappedRequest,
           ResponseFormat = WebMessageFormat.Json, UriTemplate = "/checkEmail")]
RestResponse<bool> checkEmail(string EmailId);

JSON request is:

{ "EmailId" :"youremail@yahoo.com" }

It is working as expected. But after some code review changes I changed the param in method to

checkEmail(string emailId);

ie changed it in to camel case. How can I modify my code to use same JSON request ie API call should remain same

{ "EmailId" :"youremail@yahoo.com" }

This might work for you. It works in a limited test I did. I created a class which has two properties:

[DataContract]
public class EmailParms
{
    [DataMember]
    [JsonProperty(DefaultValueHandling=DefaultValueHandling.IgnoreAndPopulate)]
    public virtual string EmailId { get; set; }
    [DataMember]
    [JsonProperty(DefaultValueHandling=DefaultValueHandling.IgnoreAndPopulate)]
    public virtual string emailId { get; set; }
}

The JsonPropertyAttribute is part of Json.NET .

And then you change your checkEmail to have:

RestResponse<bool> checkEmail(Emailparms emailParms);

The IgnoreAndPopulate basically deserializes a property that is missing from that json data, and gives it the property's default value.

Now, in your method, you just have to check the values of emailId and EmailId in emailParms and decide which to use.

In my test, it worked for any of these:

{ "EmailId" :"youremail@yahoo.com" }
{ "emailId" :"youremail@yahoo.com" }
{ "EmailId" :"youremail@yahoo.com", "emailId" :"youremail@yahoo.com" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM