(转)WebApi返回Json格式字符串
原文地址:https://www.cnblogs.com/elvinle/p/6252065.html
WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好.
先贴一下, 网上给的常用方法吧.
方法一:(改配置法)
找到Global.asax文件,在Application_Start()方法中添加一句:

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

这样返回的结果就都是json类型了,但有个不好的地方,如果返回的结果是String类型,如123,返回的json就会变成"123";
解决的方法是自定义返回类型(返回类型为HttpResponseMessage)
public HttpResponseMessage PostUserName(User user)
{
String userName = user.userName;
var result = new HttpResponseMessage{ Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json")};
return result;
}
方法二:(万金油法)
方法一中又要改配置,又要处理返回值为String类型的json,甚是麻烦,不如就不用webapi中的的自动序列化对象,自己序列化后再返回

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;
}

为了不在每个接口中都反复写那几句代码,所以就封装为一个方法这样使用就方便多了。

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;
}

方法三:(最麻烦的方法)
方法一最简单,但杀伤力太大,所有的返回的xml格式都会被毙掉,那么方法三就可以只让api接口中毙掉xml,返回json
先写一个处理返回的类:

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;
}
}

找到App_Start中的WebApiConfig.cs文件,打开找到Register(HttpConfiguration config)方法
添加以下代码:
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
添加后代码如下:

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

方法三如果返回的结果是String类型,如123,返回的json就会变成"123",解决方法同方法一。
其实WebApi会自动把返回的对象转为xml和json两种格式并存的形式,方法一与方法三是毙掉了xml的返回,而方法二是自定义返回。
以上三种方法, 就是我找到的比较普遍的方法了. 但是总觉得并不是那么好. 都要改这改那的.
还有一种方式能返回json格式字符串. 先看一下效果吧.

public class HomeController : ApiController
{
[HttpGet]
public JsonData Know(string msg)
{
msg = "WebApi 已接收到信息" ;
return new JsonData() { Content = new List<string>() { "a", "b", "c" }, IsSuccess = true, Message = msg };
} public List<string> Get()
{
return new List<string>() { "a", "b", "c"};
}
}



看的出来, Know方法返回的是 json 格式的字符串, Get方法, 返回的是xml格式的.
从上面来看, 主要是返回值不一样. 那么JsonData里面有什么秘密呢?

public class JsonData : ISerializable
{
#region 属性 /// <summary>
/// 表示业务是否正常
/// </summary>
public bool IsSuccess { get; set; } /// <summary>
/// 返回消息,成功的消息和错误消息都在这里
/// </summary>
public string Message { get; set; } /// <summary>
/// 用于返回复杂结果
/// </summary>
public object Content { get; set; }
#endregion #region 方法
/// <summary>
/// 自定义序列化方法
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
// 运用info对象来添加你所需要序列化的项
info.AddValue("IsSuccess", IsSuccess);
info.AddValue("Message", Message);
if (Content != null)
{
info.AddValue("Content", Convert.ChangeType(Content, Content.GetType()));
}
else
{
info.AddValue("Content", null);
}
} public JsonData() { }
#endregion
}

这里主要是要实现 ISerializable 接口 .
可能有人注意到, 我访问api的时候, 路由模式和访问mvc是一样的, 其实这里很简单, 只需要在webapi路由注册哪里, 加入一个路由就可以了.
config.Routes.MapHttpRoute(
name: "DefaultApi1",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
这样, 就加入了一个路由匹配规则进去. 只不过, 需要在Know方法上面, 加上一些访问限制条件. 如httpget, 否则, 如果直接去访问, 是不可以的.
(转)WebApi返回Json格式字符串的更多相关文章
- WebApi返回Json格式字符串
WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好. 先贴一下, 网上给的常用方法吧. 方法一:(改配置法) 找到Global.asax文件,在 ...
- webapi返回json格式优化
一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 config.Formatters.Remove(config.For ...
- webapi返回json格式优化 转载https://www.cnblogs.com/GarsonZhang/p/5322747.html
一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 1 config.Formatters.Remove(config.F ...
- webapi返回json格式,并定义日期解析格式
1.webapi返回json格式 var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferen ...
- WebAPI搭建(二) 让WebAPI 返回JSON格式的数据
在RestFul风格盛行的年代,对接接口大多数人会选择使用JSON,XML和JSON的对比传送(http://blog.csdn.net/liaomin416100569/article/detail ...
- 如何让Asp.net webAPI返回JSON格式数据
ASP.NET Web API 是新一代的 HTTP 網路服務開發框架,除了可以透過 Visual Studio 2012 快速開發外 (內建於 ASP.NET MVC 4 的 Web API 專案範 ...
- 指定webapi 返回 json 格式 ; GlobalConfiguration.Configuration.Formatters.Clear()
因为 Internet Explorer 和 Firefox 发送了不同的 Accept 头,所以 web API 在响应里就发送了不同的内容类型. 解决方法,在 Global.asax的 App ...
- ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)
相关博文:ASP.NET Core WebApi 返回统一格式参数 业务场景: 统一返回格式参数中,如果包含 Null 值,调用方会不太好处理,需要替换为空字符串,示例: { "respon ...
- JSon_零基础_001_将布尔类型数组转换为JSon格式字符串,返回给界面
将布尔类型数组转换为JSon格式字符串,返回给界面 需要导入包: 编写bean: package com.west.webcourse.po; /** * 第01步:编写bean类, * 下一步com ...
随机推荐
- What is the difference between concurrency, parallelism and asynchronous methods?
Ref: http://stackoverflow.com/questions/4844637/what-is-the-difference-between-concurrency-paralleli ...
- mysql主从复制--重置操作reset master, reset slave
本文介绍reset master, reset slave的作用. reset master 在master上执行 mysql > RESET MASTER 作用包括: 删除binlog索引文件 ...
- Hadoop YARN上运行MapReduce程序
(1)配置集群 (a)配置hadoop-2.7.2/etc/hadoop/yarn-env.sh 配置一下JAVA_HOME export JAVA_HOME=/home/hadoop/bigdata ...
- sql日期操作
日期格式化函数 ), ): :57AM ), ): ), ): ), ): ), ): ), ): ), ): ), ): , ), ): :: ), ): :::827AM ), ): ), ): ...
- R基于Bayes理论实现中文人员特性的性别判定
参见 基于中文人员特征的性别判定方法 理论,告诉一个名字,来猜猜是男是女,多多少少有点算命的味道.此命题是一种有监督的学习方法,从标注好的训练数据学习到一个预测模型,然后对未标注的数据进行预测. 1 ...
- MYSQL优化浅谈,工具及优化点介绍,mysqldumpslow,pt-query-digest,explain等
MYSQL优化浅谈 msyql是开发常用的关系型数据库,快速.稳定.开源等优点就不说了. 个人认为,项目上线,标志着一个项目真正的开始.从运维,到反馈,到再分析,再版本迭代,再优化… 这是一个漫长且考 ...
- InfluxDB 常用命令
查表: http://192.168.0.200:8086/query?q=select+*+from+telegraf..cpu http://192.168.0.200:8086/query?q= ...
- centos su命令
有很多指令都只可以用 root 身份去执行,因此我们需要成为 root 用户.要这样做,我们可以使用 su 指令(更替用户).su 指令有下列格式: su - <user>或su < ...
- 【sql】之case when then else end
select a.`name`, sum(( END)) '语文', sum(( END)) '数学', sum(( END))'英语' from t_score a GROUP BY a.`name ...
- TCP/IP学习20180627-数据链路层-ethernet
ifconfig :查看主機支持的網絡協議eth0:以太網接口lo:loopback接口 以太网(Ether-net)的定是指数字设备公司( Digital Equipment Corp.).英特尔公 ...