开发者

Mapping Complex Type in REST Enabled WCF Service

开发者 https://www.devze.com 2022-12-10 15:30 出处:网络
I m trying to rest-ify our existing WCF service and one of the hurdle is mapping complex type using Uritemplate. For example take a look at the below code

I m trying to rest-ify our existing WCF service and one of the hurdle is mapping complex type using Uritemplate. For example take a look at the below code

[DataContract]
public class Stock
{
    [DataMember]
    public string Symbol { get;set; }
    [DataMember]
    public double FaceValue { get; set; }
}

[ServiceContract]
public interface IRestService
{       
    [OperationContract]
    [WebGet(UriTemplate = "?Symbol={stk.Symbol开发者_运维问答}")]
    void Test1(Stock stk); 
}

The above Uritemplate declaration will definitely not work, but this is what is my intention of mapping the input query variable to one of the property of that object.. Is this possible ?

Tks in advance for your help.


The example you give doesn't illustrate the problem. In that case, all that's needed is to pass a stock symbol, a simple string, and there's no need for a complex type.

In cases where you want to pass a more complex set of data, a JSON-encoded object, use WebInvoke with PUT or POST, a non-parameterized UriTemplate, and pass form data. See this answer for details.

In cases where you want GET, and can pass a small set of discrete parameters, you can use WebGet, an appropriate UriTemplate, and do the manual mapping. like so:

public enum OptionFlavor { Put, Call }
public class OptionInqury { public String Symbol; public String Month; public OptionFlavor Flavor;}

[OperationContract] 
[WebGet(UriTemplate = "/optionquote/{stockSymbol}/{month}/{flavor}")] 
void GetOptionPrice(string stockSymbol, string month, string flavor)
{
   var x = new OptionInquiry { 
       Symbol = stockSymbol, 
       Month = month,
       Flavor = (flavor.Equals("put")) ? OptionFlavor.Put : OptionFlavor.Call
   };
   // off you go...
}


If you want to map your query string parameters to the properties in your object, you need to go with WebInvoke. Unfortunately with GET, you will have to do this manually.

0

精彩评论

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