Home Backend Development C#.Net Tutorial Two methods to set C# web api return type to json

Two methods to set C# web api return type to json

Jan 19, 2017 am 10:39 AM

When web api writes an api interface, the default return is to serialize your object and return it in XML form. So how can you make it return as json? Here are two methods:
Method 1: (Change Configuration method)

Find the Global.asax file and add a sentence in the Application_Start() method:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
Copy after login

After modification:

<br>protected void Application_Start() <br>{ <br>AreaRegistration.RegisterAllAreas();
 <br>WebApiConfig.Register(GlobalConfiguration.Configuration); 
 <br>FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
 <br>RouteConfig.RegisterRoutes(RouteTable.Routes); 
 <br>// 使api返回为jsonGlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();} <br>
Copy after login

The results returned in this way will be It is of json type, but there is a disadvantage. If the returned result is of String type, such as 123, the returned json will become "123";

The solution is to customize the return type ( The return type is HttpResponseMessage)

public HttpResponseMessage PostUserName(User user)   
{   
String userName = user.userName;   
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") };   
return result;   
}
Copy after login

Method 2: (One-size-fits-all method)

Method 1 requires changing the configuration and processing json whose return value is String type. It is very troublesome, so why not just Instead of using the automatic serialization object in the web api, serialize it yourself and then return it.

public HttpResponseMessage PostUser(User user)   
{   
JavaScriptSerializer serializer = new JavaScriptSerializer();   
string str = serializer.Serialize(user);   
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };   
return result;   
}
Copy after login

Method 2 is my more recommended method. In order not to repeatedly write those few lines of code in every interface, I encapsulate it. It is much more convenient to use it this way for a method.

public static HttpResponseMessage toJson(Object obj)   
{   
String str;   
if (obj is String ||obj is Char)   
{   
str = obj.ToString();   
}   
else   
{   
JavaScriptSerializer serializer = new JavaScriptSerializer();   
str = serializer.Serialize(obj);   
}   
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };   
return result;   
}
Copy after login


Method three: (the most troublesome method)

Method one is the simplest, but it is too lethal, and all returned xml formats will be destroyed. Then method three can only kill the xml in the api interface and return json

First write a class to process the return:

public class JsonContentNegotiator : IContentNegotiator   
{   
private readonly JsonMediaTypeFormatter _jsonFormatter;   
  
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)   
{   
_jsonFormatter = formatter;   
}   
  
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)   
{   
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));   
return result;   
}   
}
Copy after login

Find the WebApiConfig.cs file in App_Start, open it and find Register( HttpConfiguration config) method

Add the following code:

var jsonFormatter = new JsonMediaTypeFormatter();   
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
Copy after login

The code after adding is as follows:

<br>public static void Register(HttpConfiguration config) <br>{ <br>config.Routes.MapHttpRoute( 
<br>name: "DefaultApi", <br>routeTemplate: "api/{controller}/{action}/{id}", <br>defaults: new { 
id = RouteParameter.Optional } <br>);var jsonFormatter = new JsonMediaTypeFormatter();   
onfig.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));} <br>
Copy after login

Method 3 If the returned result is String type, such as 123, return The json will become "123", and the solution is the same as method one.

In fact, web api will automatically convert the returned object into a form in which xml and json formats coexist. Methods 1 and 3 eliminate the return of xml, while method 2 is to customize the return.

The above is the content of the two methods of setting the C# web api return type to json. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles