A summary of some problems in data transmission format using JSON _json

Source: Internet
Author: User
Tags exception handling
How to provide JSON data to clients
I. Using WCF to provide JSON data
Providing JSON data to clients with WCF we need to be aware that
A. The definition of the contract, the Responseformat in WebInvokeAttribute or WebGetAttribute is set to Webmessageform.json,
Copy Code code as follows:

[WebInvoke (method = "POST", Responseformat = Webmessageformat.json, Requestformat = Webmessageformat.json, BodyStyle = We Bmessagebodystyle.bare)]
[WebGet (Responseformat = Webmessageformat.json, UriTemplate = "Isexistssid/{ssid}", Requestformat = Webmessageformat.json, bodystyle = Webmessagebodystyle.bare)]

B. Endpointbehavior use of Webhttp
Copy Code code as follows:

<behavior name= "Uiajaxendpointbehavior" >
<webhttp/>
<policyendpointbehavior/>
</behavior>

C. Use of webhttpbinding in Binding mode
Copy Code code as follows:

<service name= "XX. Deviceuiservice "behaviorconfiguration=" Uiajaxservicebehavior ">
<endpoint address= "" behaviorconfiguration= "Uiajaxendpointbehavior"
binding= "WebHttpBinding" contract= "Deviceuiservicecontract"/>
</service>

Two. Provide JSON data with the. Net MVC Action
1. In ValueProviderFactories.Factories.Add (new Jsonvalueproviderfactory ()) to add the processing of Json data, MVC 3 is joined by default, if you are using MVC3, There is no need to ignore this point.
2. Use Jsonresult as the return value of your action.
3. Returns are using return Json (XXX); XXX is the data you want to return, and its data type must be serializable type.
three. Can be achieved by using the simple webservice of ASMX as the suffix name,
Four. Use the HttpHandler mechanism to achieve.
Because WCF has been defined by Microsoft as Microsoft's communications platform, the latter two can be implemented, but is an earlier implementation, so I used WCF, directly to the data provided by the system as the data provided interface.
In the context of. NET MVC, the output of JSON-type data has been directly supported, so you choose WCF provision in a non. NET MVC environment, and you directly choose to use JSON action support in the. NET MVC environment.
Web Client Processing
Using jquery ajax to process
Set datatype to ' JSON ' format, which automatically converts result to JSON object format when receiving data.
Copy Code code as follows:

$.ajax ({
URL: ' urladdress '
Type: ' Get ',
ContentType: ' Application/json ',
DataType: ' JSON ',
Cache:false,
Async:false,
Error:jqueryajaxerrorhandler,
Success:function (Result) {}
});

Consideration of exception handling

Here I mainly consider in the Web environment exception processing, according to the HTTP protocol definition, each request will return an HTTP Status code, different code represents a different meaning. So our web application should also be like this, returning different HTTP Status Code based on different results, such as 200, representing the correct return on the server, 417 for the server exception we expect, 404, the request does not exist, and 301 of our unauthorized.

In a WCF environment, we first add faultcontract to each method, as follows:
Faultcontract (typeof (Webfaultexception<weberrordetail>))
Secondly, we have to do some processing of the exception, so that the server can return the correct HTTP Status Code.

Copy Code code as follows:

Try
{
Bussinesscode .....
}
catch (Duplicateexception ex)
{
throw new webfaultjsonformatexception<weberrordetail> New Weberrordetail (ex. Message, ex), httpstatuscode.expectationfailed);
}
catch (Notexistexception ex)
{
throw new webfaultjsonformatexception<weberrordetail> New Weberrordetail (ex. Message, ex), httpstatuscode.expectationfailed);
}
catch (Appexception ex)
{
throw new webfaultjsonformatexception<weberrordetail> New Weberrordetail (ex. Message, ex), httpstatuscode.expectationfailed);
}
catch (Exception ex)
{
throw new webfaultjsonformatexception<weberrordetail> New Weberrordetail (ex. Message, ex), httpstatuscode.expectationfailed);
}
The signatures of the webfaultjsonformatexception are as follows:
[Serializable, DataContract]
public class Webfaultjsonformatexception<t>: webfaultexception<t>
{
Public Webfaultjsonformatexception (T detail, HttpStatusCode statusCode)
: Base (detail, StatusCode)
{
Errordetailtypevalidator (detail);
}
Public Webfaultjsonformatexception (T detail, HttpStatusCode statusCode, ienumerable<type> 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<pureweberrordetail> New Pureweberrordetail ("The DataContractAttribute The property ' IsReference ' which applied in {0} can ' t be true while 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;}
}

Because when we do data transfer in JSON, the isreference in DataContract is not true, meaning that XML is a circular reference that can support data relative to XML, and JSON is not supported, So the role of webfaultjsonformatexception is to determine whether the DataContract isreference of our JSON data type is true and, if so, to return an error message that we have defined well. If this definition is not adopted, JQUery Ajax is the HTTP Status Code that the problem receives??? An error code, but this error code is not our normal HTTP Status code scope.

a misunderstanding of exception handling
The earliest time, because did not think in this way processing, is also long write code to commit a malady, to each method adds a fixed generic return value type
Copy Code code as follows:

[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<t>: Tmresult
where T:class
{
[DataMember]
Public T Model {get; set;}
}

Every time you return, there is a success to represent the success, errormessage the error message in the wrong case, in the way that every HTTP status Code you return is 200, and then you know that after you think of the solution above, Just feel that we do not need to make such a complex, since it is the web, then why not write the program more in line with the definition of HTTP protocol, that would not be simpler.

Therefore, we also experience the benefits of various standards, familiar with the standard, familiar with the programming model and various APIs, our development will be simpler and easier.
The above is written according to the individual understanding, there is the wrong place please correct me.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.