The C # Web API return type is set to JSON in two ways

Source: Internet
Author: User
Tags tojson

Every time you write a blog, the first sentence is this: the programmer is very hard, in addition to writing procedures, but also to write a blog! Of course, hope that the future day, a boss see this blog, to your programmer staff pay bar! Because the programmer's world is silent except bitter force. Most of the programmers in my eyes do not love to talk, silently bear the great pressure of programming, in addition to technical exchanges, they do not want to be good at communicating with others, but also not willing to anyone into their hearts!

Realize a reason, here to share to everyone: education represents your past, the ability to represent your present, study represents your future. We all know that the computer technology is developing rapidly, the speed is amazing fast, you and I are not careful, will be slowly eliminated! Therefore: daily uninterrupted learning is the magic weapon to avoid being eliminated.

Needless to say, the direct topic is as follows:

ASP. NET Web API

(referred to as the Web API), is an application framework built on the ASP.

The Web API is based on a special controller that is added to an MVC application, called an API controller, which has the following two distinct characteristics compared to the MVC normal controller:

    1. The Action method returns a Model object, not a ActionResult.
    2. when requested, the Action method is selected based on the HTTP request mode .

The model object returned to the client from the API Controller's action method is JSON-encoded. The API controller is designed only to provide services that deliver web data, so it does not support view, Layout, and other HTML rendering-related features. The web API can support any web-enabled client, but the most common is to service AJAX requests in Web applications.

In general we will choose to use the API Controler in the following two cases:

    1. A large number of action methods are required to return JSON-formatted data.

2. Nothing to do with HTML, just to serve the data purely.

Beginners Webapi, we make the default return type of the program is XML format, then how to return the JSON type format data? There are two ways to do this:

Method One: (Change the Configuration method)

Locate the Global.asax file, and add the following paragraph in the Application_Start () method: The code is as follows:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear (); This method is too lethal, and all the returned XML formats will be killed, so be careful to choose according to the actual needs.

Method Two: (Balm method)

Create a new class: The code is as follows:

  Public classResulttojson { Public Statichttpresponsemessage ToJson (Object obj) {String str; if(obj isString | | Obj isChar) {STR=obj.            ToString (); }            Else{JavaScriptSerializer Serializer=NewJavaScriptSerializer (); STR=Serializer.            Serialize (obj); } httpresponsemessage result=Newhttpresponsemessage {Content =NewStringcontent (str, encoding.getencoding ("UTF-8"),"Application/json") }; returnresult; }     }

Note: A reference to the JavaScriptSerializer namespace, from MSDN, is as follows:

namespaces: System.Web.Script.Serialization
Assemblies: System.Web.Extensions (in System.Web.Extensions.dll)

The case code is as follows:

[HttpGet] Publichttpresponsemessage Get () {List<Person> list =NewList<person>();  for(inti =0; I <Ten; i++) {person P=NewPerson () {Name="Name"+I, age=I, Sex= i%2==0?"M":"W"                }; List.            ADD (P); }            returnResulttojson.tojson (list); }
  Public classPerson {Private intAge ;  Public intAge {Get{returnAge ;} Set{age =value;} }        Private stringname;  Public stringName {Get{returnname;} Set{name =value;} }        Private stringsex;  Public stringSex {Get{returnsex;} Set{sex =value;} }    }

The Balm method belongs to the custom return, which is recommended in cases where XML returns cannot be killed.

Study hard, make progress every day, beginner/self-study webapi, step by step, do not be impatient, one step at a stage, always rise.

@ Chen Wolong's blog

The C # Web API return type is set to JSON in two ways

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.