Summary of some issues in using JSON as data transmission format_json
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,
[ 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
C. Binding method uses webHttpBinding
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.
$.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.
try
{
//BussinessCode.....
}
catch (DuplicateException ex)
{
throw new WebFaultJsonFormatException
}
catch (NotExistException ex)
{
throw new WebFaultJsonFormatException
}
catch (AppException ex)
{
throw new WebFaultJsonFormatException
}
catch (Exception ex)
{
throw new WebFaultJsonFormatException
}
其中WebFaultJsonFormatException的签名如下:
[Serializable, DataContract]
public class WebFaultJsonFormatException
{
public WebFaultJsonFormatException(T detail, HttpStatusCode statusCode)
: base(detail, statusCode)
{
ErrorDetailTypeValidator(detail);
}
public WebFaultJsonFormatException(T detail, HttpStatusCode statusCode, IEnumerable
: 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
}
}
}
[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
where T : class
{
[DataMember]
public T Model { get; set; }
}
每次返回都会有一个Success代表是否成功, ErrorMessage代表错误情况下的错误信息, 这样做的方式其实就是每次返回的 HTTP Status Code 都是200, 后来知道想到上面的解决办法之后,才觉得我们更本不需要搞的这么复杂,既然是Web, 那干吗不把程序写的更符合HTTP协议的定义, 那样岂不更简单。
所以在此也体会到各种标准的好处, 熟悉标准,熟悉编程模型及各种API, 我们的开发会更简单,更轻松.
以上都是按个人理解所写,有不对之处请指正.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

How to make concurrent GET requests for multiple links and judge in sequence to return results? In Tampermonkey scripts, we often need to use multiple chains...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.