简体   繁体   中英

Wcf rest service with json response and service status

I have WCF REST service returns a JSON response like

{
    "categories": [{
        "category_id": "10",
        "name": "Grocery",
        "freeQnty":"0",
        "prdcost":"100"
    }, {
        "category_id": "20",
        "name": "Beverages",
        "freeQnty":"1",
        "prdcost":"20"  
    }]
}

But i want response with service status like.

{
    "success": true,
    "categories": [{
        "category_id": "10",
        "name": "Grocery",
        "freeQnty":"0",
        "prdcost":"100"
    }, {
        "category_id": "20",
        "name": "Beverages",
        "freeQnty":"1",
        "prdcost":"20"  
    }]
}

and this is my services.

[OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/GetCustomerDetails/{customerid}")]
        Merchant GetCustomerDetails(string customerid);


[DataContract]
    public class categories
    {
        [DataMember]
        public int category_id{ get; set; }

        [DataMember]
        public string name { get; set; }

        [DataMember]
        public int freeQnty{ get; set; }

        [DataMember]
        public int prdcost { get; set; }
    }

how to get that success status if service success i need to show "success": true other wise "success": false.

Possible variant:

[OperationContract]
[WebInvoke(
BodyStyle = WebMessageBodyStyle.Bare, //or WrappedRequest
Method = "GET",
ResponseFormat = WebMessageFormat.Json,     
UriTemplate = "/somemethod?param1={param1}&param2={param2}")]
System.ServiceModel.Channels.Message SomeMethod(string param1, string param2)
{
    // use JSON.NET to add missing properties etc: 
    var jObject = JObject.FromObject(yourObject); 
    jObject["success"] = true; 
    var json = jObject.ToString();

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
    return WebOperationContext.Current.CreateTextResponse(json);
}

Better to change your response contract. Create a new response class with members success and categories as below and return that

  [DataContract]
  public class YourResponse
{
    [DataMember]
    public bool Success { get; set; }

    [DataMember]
    public categories Categories{ get; set; }
}

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