Home >Web Front-end >JS Tutorial >Summary of some issues in using JSON as data transmission format_json

Summary of some issues in using JSON as data transmission format_json

WBOY
WBOYOriginal
2016-05-16 17:58:071206browse

Ways to provide JSON data to the client
1. Use WCF to provide Json data
We need to pay attention to using WCF to provide Json data to the client,
A. The definition of the contract, in WebInvokeAttribute Or the ResponseFormat in WebGetAttribute is set to WebMessageForm.Json,

Copy code The code is as follows:

[ WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "IsExistSSID/{SSID}", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]

B. EndPointBehavior uses WebHttp
Copy code The code is as follows:






C. Binding method uses webHttpBinding
Copy code The code is as follows:


binding="webHttpBinding" contract="DeviceUIServiceContract" /> ;


2. Use .Net MVC Action to provide JSON data
1. In ValueProviderFactories.Factories.Add(new JsonValueProviderFactory() ), MVC 3 adds Json data processing by default. If you are using MVC3, you don’t need to pay attention to this.
2. Use JsonResult as the return value of your Action.
3. To return, use return Json(XXX); XXX is the data you want to return, and its data type must be a serializable type.
3. A simple WebService with asmx as the suffix can be used To implement,
4. Use the HttpHandler mechanism to implement.
Because WCF has been defined by Microsoft as a communication platform under the Microsoft system, the latter two can be implemented, but they are earlier implementation methods, so Here I used WCF and directly regarded the provided data as the system's data providing interface.
In the .NET MVC environment, it has directly supported the output of data in Json form, so in non-.NET MVC The environment is provided by WCF, and in the .NET MVC environment, JSON Action support is directly selected.
WEB client processing
Using JQuery Ajax processing
Set the dataType to 'json' format, which will automatically be used when receiving data Convert result to json object format.
Copy code The code is as follows:

$.ajax( {
url: 'urladdress'
type: 'GET',
contentType: 'application/json',
dataType: 'json',
cache: false,
async: false,
error: JQueryAjaxErrorHandler,
success: function (result) { }
});

Exception handling considerations

Here I mainly consider exception handling in the Web environment. According to the definition of the HTTP protocol, each request will return an HTTP Status Code. Different Codes represent different meanings. Therefore, our web application should also be like this, returning different HTTP Status Code according to different results. For example, 200 represents the correct return from the server, 417 represents the server exception we expect, and 404 represents the request. Does not exist, etc., and 301 Our Unauthorized.

In the WCF environment, we first need to add FaultContract to each method, as follows:
FaultContract(typeof(WebFaultException))
Secondly, we need to do some processing on the exception so that the service The client can return the correct HTTP Status Code.

Copy code The code is as follows:

try
{
//BussinessCode.....
}
catch (DuplicateException ex)
{
throw new WebFaultJsonFormatException(new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
catch (NotExistException ex)
{
throw new WebFaultJsonFormatException(new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
catch (AppException ex)
{
throw new WebFaultJsonFormatException(new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
catch (Exception ex)
{
throw new WebFaultJsonFormatException(new WebErrorDetail(ex.Message, ex), HttpStatusCode.ExpectationFailed);
}
其中WebFaultJsonFormatException的签名如下:
[Serializable, DataContract]
public class WebFaultJsonFormatException : WebFaultException
{
public WebFaultJsonFormatException(T detail, HttpStatusCode statusCode)
: base(detail, statusCode)
{
ErrorDetailTypeValidator(detail);
}
public WebFaultJsonFormatException(T detail, HttpStatusCode statusCode, IEnumerable knownTypes)
: base(detail, statusCode, knownTypes)
{
ErrorDetailTypeValidator(detail);
}
private void ErrorDetailTypeValidator(T detail)
{
foreach (DataContractAttribute item in detail.GetType().GetCustomAttributes(typeof(DataContractAttribute), true))
{
if (item.IsReference)
throw new WebFaultJsonFormatException(new PureWebErrorDetail("The DataContractAttribute property 'IsReference' which applied on {0} can't be true when the transfer code type is JSON fromat.", typeof(T).FullName), HttpStatusCode.ExpectationFailed);
}
}
}
[Serializable, DataContract(IsReference = false)]
public class PureWebErrorDetail
{
public PureWebErrorDetail(string message, params object[] args)
{
this.Message = string.Format(message, args);
}
[DataMemberAttribute]
public string Message { get; set; }
}

因为我们在JSON做数据传输的时候, DataContract中的IsReference是不可以为true的,其意思是相对于XML来说的,XML是可以支持数据的循环引用, 而JSON是不支持的,所以WebFaultJsonFormatException的作用就在于判断当前我们的JSON数据类型的DataContract的IsReference是否为true, 如果是,则返回一个我们定义好的错误信息. 如果没有采用这个定义,JQUery Ajax因此问题接收到的 HTTP Status Code 是15???的一个错误代码, 但这个错误代码并不是我们正常的 HTTP Status Code 范围.

异常处理的一个误区
最早的时候,由于没想到用这个方式处理,也是长久写代码犯下的一个弊病, 给每个方法加了一个固定的泛型返回值类型
复制代码 代码如下:

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

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

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

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

[DataContract]
public class TmResult : TmResult
where T : class
{
[DataMember]
public T Model { get; set; }
}

每次返回都会有一个Success代表是否成功, ErrorMessage代表错误情况下的错误信息, 这样做的方式其实就是每次返回的 HTTP Status Code 都是200, 后来知道想到上面的解决办法之后,才觉得我们更本不需要搞的这么复杂,既然是Web, 那干吗不把程序写的更符合HTTP协议的定义, 那样岂不更简单。

所以在此也体会到各种标准的好处, 熟悉标准,熟悉编程模型及各种API, 我们的开发会更简单,更轻松.
以上都是按个人理解所写,有不对之处请指正.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn