从WCF中的operationcontract返回JSON的好习惯 [英] Good practice to return JSON from operationcontract in WCF

查看:92
本文介绍了从WCF中的operationcontract返回JSON的好习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WCF中有一个operationContract,其返回类型是一个对象,我需要将该对象以JSON格式发送给用户。现在我遇到了两种从我的方法返回JSON数据的方法。请建议采用哪种方法?将模型序列化为第二种方式是否可以提供额外的好处?



我尝试过的方法:



从我的OperationContract返回JSON数据的两种方法如下: -

1)

I am having an operationContract in WCF whose return type is an object and I need to send that object in JSON format to user. Now I have come across two ways of returning JSON data from my method. Please suggest which one is the good practice to adopt?; Does serializing the model as done in second way provides any additional benefits?

What I have tried:

The two ways of returning JSON data from my OperationContract are as followed:-
1)

[OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        public Model1 GetData(string Id1, string Id2)
        {
            try
            {
                Model1 objModel  = new Model1();
                DataSet ds = new DataSet();
                BAL objBAL = new BAL();
                objModel  = objBAL.GetData(Id1, Id2);
                return objModel  
            }
            catch (FaultException ex)
            {
                // error handling code here
            }
        }



2)
 [OperationContract]
        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
        public string GetData(string Id1, string Id2)
        {
            try
            {
                string json = string.Empty;
                Model1 objModel  = new Model1();
                DataSet ds = new DataSet();
                BAL objBAL = new BAL();
                objModel  = objBAL.GetData(Id1, Id2);
                json = new JavaScriptSerializer().Serialize(objModel);
                return json;
            }
            catch (FaultException ex)
            {
                // error handling code here
            }
        }

推荐答案

第一个选项将返回结果的JSON编码表示。



第二个选项将返回JSON -encoded字符串,包含结果的JSON编码表示。



除了服务器上的额外工作,JSON编码结果两次,第二个选项将还需要在接收端进行额外的工作。
The first option will return a JSON-encoded representation of the result.

The second option will return a JSON-encoded string containing a JSON-encoded representation of the result.

Aside from the extra work involved on the server to JSON-encode the result twice, the second option will also require extra work on the receiving end.


这篇关于从WCF中的operationcontract返回JSON的好习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆