使用 asp.net Web API 2的坑

本文介绍如何在Web API中定制JSON响应格式,包括缩进、大小写处理、空值管理、日期时间格式设置等,并提供了具体代码示例。

使用工具:

Googl  浏览器+PostMan 插件

写了个  控制器 

添加了个Action,结果呢?GET 方式请求没问题。

POST一直,在服务器端获取不了参数。。。找了官方的文档 。各种雨里雾里。

总而言之,post 方式,推荐将数据封闭到一个类中,然后整体提交Json数据,或者Xml数据。首选是Json

POST提交表单

1 键值对的方式

2 Body 的方式

其中 键值对的方式 又分为  URI的键值对  ,form-data的键值对,application/x-www-form-urlencoded的键值对

Body的方式,又根据 Content-Type 分为不同的类型 《json ,xml,text/html.......》

其实好乱。。。就用json 即可。

使用json 的时候,发送的时候 ,使用的编码集,请首选 UTF-8...因为。他就支持 UTF8 UNICODE俩编码集

var encodings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedEncodings;

 

//config.Formatters.JsonFormatter.SupportedEncodings.Clear();
//config.Formatters.JsonFormatter.SupportedEncodings.Add(System.Text.Encoding.Default);

 

不信自己试试去吧。。。。

 

 

简易参数,必须 int string   。使用frombody。。。标注。。。。最好不要使用简易类型,你会很蛋疼。不信试试。。。。

frombody的对立是 fromUri。。。。。

额 。。。

 

参考自定义 JSON 格式化器,在web API中。

 

 

 my previous post I wrote about Web API and the content negotiation. In this post I’d like to describe how it’s easy to change the Json serialization.

The most important improvement from the Beta to the RC in the Web API is about the serialization, in fact now the framework is using Json.Net for the serialization. For all people who don’t know what Json.Net is I can say, to make the definition easily, Json.Net is the best serializer in the .NET world.

It's cool for many reasons, especially because it's flexible and easy to setup. In this post I’d like to show the principals and useful settings that you probably want to change in your application, or can be helpful for you in the future.

Before to start, we have to make our Web API project easy to debug so, I’m going to remove the XML formatter. I’m doing that because I’m in a test project and I’d like to see the response in the browser. The easily way to force the response to Json for all Web API requests is to remove the XML. Obviously you shouldn't do it in production.

NOTE: All code in this post,except the last one, must be located into the global.asax.cs

var formatters = GlobalConfiguration.Configuration.Formatters; formatters.Remove(formatters.XmlFormatter); 

Now we can start change the setting for all Json responses accessing toGlobalConfiguration.Configuration.Formatters.JsonFormatter.

In the following examples I’ll use always the class below:

public class User
{
  public string Firstname { get; set; } public string Lastname { get; set; } public string Username { get; set; } public DateTime Birthdate { get; set; } public Uri Website { get; set; } public int Age { get; set; } public double Salary { get; set; } [JsonIgnore] public string IgnoreProperty { get; set; } } 

How can we indent the json response?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; 

How can we change the case in the response?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); 

How can we manage the null in the response?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; 

How can we change the DateTime format?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; 

How can we change the TimeZone format?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; 

How can we change the Culture of the serializer?

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; json.SerializerSettings.Culture = new CultureInfo("it-IT"); 

Another cool feature of Web API is to opportunity to override the configuration for a single response. You can use all of the previous setting directly in the single action like explained in the code below:

public HttpResponseMessage Get(){
  IList<User> result = new List<User>(); result.Add(new User { Age = 34, Birthdate = DateTime.Now, Firstname = "Ugo", Lastname = "Lattanzi", IgnoreProperty = "This text should not appear in the reponse", Salary = 1000, Username = "imperugo", Website = new Uri("http://www.tostring.it") }); var formatter = new JsonMediaTypeFormatter(); var json =formatter.SerializerSettings; json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; json.Formatting = Newtonsoft.Json.Formatting.Indented; json.ContractResolver = new CamelCasePropertyNamesContractResolver(); json.Culture = new CultureInfo("it-IT"); return Request.CreateResponse(HttpStatusCode.OK, result, formatter); } 

Such as ASP.NET MVC, Web API are really flexible ... and ROCKS!

 

参考文献:

http://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1

http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

http://www.cnblogs.com/zgynhqf/p/3180527.html

http://tostring.it/2012/07/18/customize-json-result-in-web-api/

https://dotblogs.com.tw/yc421206/archive/2013/11/11/127593.aspx#webrequest-post

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值