Home Backend Development C#.Net Tutorial Let WebAPI return data in JSON format tutorial

Let WebAPI return data in JSON format tutorial

May 21, 2018 am 11:10 AM
api javascript json web webapi build return

In the era when the RestFul style is prevalent, most people will choose to use JSON, XML and JSON comparison transmission () for docking interfaces. Let’s see what this blogger said. Although he didn’t finish it in the end, I think it’s probably the same. It can slightly resolve the doubts in my mind.

1. In fact, it is very simple to make WebAPI return data in JSON format. Just configure it in the ConfigureWebapi method. Previously two namespaces needed to be referenced.

using Newtonsoft.Json.Serialization;using System.Linq;
Copy after login

2. The core code is as follows:

var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<system.net.http.formatting.jsonmediatypeformatter>().First();
 jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由config.MapHttpAttributeRoutes();</system.net.http.formatting.jsonmediatypeformatter>
Copy after login

The complete code is as follows:

        /// <summary>/// 配置WebApi/// </summary>/// <param>public void ConfigureWebapi(IAppBuilder app)
        {//创建一个HTTP的实例配置var config = new HttpConfiguration();var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器            config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<system.net.http.formatting.jsonmediatypeformatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由            config.MapHttpAttributeRoutes();//映射路由            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );//将配置注入OWIN管道中            app.UseWebApi(config);
        }</system.net.http.formatting.jsonmediatypeformatter>
Copy after login

3 .Next let us test it, add a Controller named ProductController, delete all methods, and add a GetProductList method, the code is as follows:

       [HttpGet]public HttpResponseMessage GetProduct()
        {var product = new { id = 1, name = "三星王炸" };

            HttpResponseMessage result = new HttpResponseMessage();
            result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result;
        }
Copy after login

4. Enter http://localhost in the browser :27650/api/product/GetProduct, the output result is

Let WebAPI return data in JSON format tutorial

5. We found that if we enter http://localhost:27650/api/product in the browser, the same The return value can be obtained, let us simply transform it and write a new method

        [HttpGet]public HttpResponseMessage GetProduct2(string id)
        {var product = new { id = id, name = "三星王炸" };

            HttpResponseMessage result = new HttpResponseMessage();
            result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result;
        }
Copy after login

6. Enter http://localhost:27650/api/product?id in the browser =3 and http://localhost:27650/api/product, the results obtained are

Let WebAPI return data in JSON format tutorialLet WebAPI return data in JSON format tutorial

Why does this happen? Let’s take a look. When configuring the routing rules of WebAPI, the rule is api/{controller}/{id}, which means that this rule will not match the name of the action, but will be determined based on the type and number of parameters passed in.

Let WebAPI return data in JSON format tutorial

7. So how to make WebAPI match according to the method name? Let us modify the routing rules. The code is as follows:

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
Copy after login

8. Let us test it again. Enter http://localhost:27650/api/product in the browser to see the effect.

Let WebAPI return data in JSON format tutorial

Then enter http://localhost:27650/api/product/GetProduct and http://localhost:27650/api/product/GetProduct?id=5 and found The two returned results are the same, indicating that the same method is accessed.

Let WebAPI return data in JSON format tutorialLet WebAPI return data in JSON format tutorial

Then enter http://localhost:27650/api/product/GetProduct2 and http://localhost:27650/api/product/GetProduct2?id= 6

Result:

Let WebAPI return data in JSON format tutorial

Let WebAPI return data in JSON format tutorial

##The test passed.

This is just for organizing and deepening the impression in case you forget. If there is anything incorrect, please feel free to give us your advice.

The above is the detailed content of Let WebAPI return data in JSON format tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

How to implement h5 to slide up on the web side to load the next page How to implement h5 to slide up on the web side to load the next page Mar 11, 2024 am 10:26 AM

Implementation steps: 1. Monitor the scroll event of the page; 2. Determine whether the page has scrolled to the bottom; 3. Load the next page of data; 4. Update the page scroll position.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

Golang's browser support: building an interactive web Golang's browser support: building an interactive web Apr 07, 2024 pm 04:03 PM

Go builds interactive web applications that run in the browser. Steps: Create Go project and main.go file, add HTTP handler to display messages. Add forms using HTML and JavaScript for user input and submission. Add handling of POST requests in your Go application, receive user messages and return responses. Use FetchAPI to send POST requests and handle server responses.

See all articles