原文地址: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格式字符串的更多相关文章

  1. WebApi返回Json格式字符串

    WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好. 先贴一下, 网上给的常用方法吧. 方法一:(改配置法) 找到Global.asax文件,在 ...

  2. webapi返回json格式优化

    一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 config.Formatters.Remove(config.For ...

  3. webapi返回json格式优化 转载https://www.cnblogs.com/GarsonZhang/p/5322747.html

    一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 1 config.Formatters.Remove(config.F ...

  4. webapi返回json格式,并定义日期解析格式

    1.webapi返回json格式 var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferen ...

  5. WebAPI搭建(二) 让WebAPI 返回JSON格式的数据

    在RestFul风格盛行的年代,对接接口大多数人会选择使用JSON,XML和JSON的对比传送(http://blog.csdn.net/liaomin416100569/article/detail ...

  6. 如何让Asp.net webAPI返回JSON格式数据

    ASP.NET Web API 是新一代的 HTTP 網路服務開發框架,除了可以透過 Visual Studio 2012 快速開發外 (內建於 ASP.NET MVC 4 的 Web API 專案範 ...

  7. 指定webapi 返回 json 格式 ; GlobalConfiguration.Configuration.Formatters.Clear()

    因为 Internet Explorer 和 Firefox 发送了不同的 Accept 头,所以 web API 在响应里就发送了不同的内容类型.   解决方法,在 Global.asax的 App ...

  8. ASP.NET Core WebApi 返回统一格式参数(Json 中 Null 替换为空字符串)

    相关博文:ASP.NET Core WebApi 返回统一格式参数 业务场景: 统一返回格式参数中,如果包含 Null 值,调用方会不太好处理,需要替换为空字符串,示例: { "respon ...

  9. JSon_零基础_001_将布尔类型数组转换为JSon格式字符串,返回给界面

    将布尔类型数组转换为JSon格式字符串,返回给界面 需要导入包: 编写bean: package com.west.webcourse.po; /** * 第01步:编写bean类, * 下一步com ...

随机推荐

  1. 利用express托管静态文件

    通过express内置的express.static可以方便的托管静态文件,例如图片.css.javascript文件等. 将静态资源文件所在的目录作为参数传递给express.static中间件就可 ...

  2. python super()函数

    super()函数是用来调用父类(超类)的一个方法 super()的语法: python 2 的用法: super(Class, self).xxx  # class是子类的名称 class A(ob ...

  3. storage 事件监听

    在公司的一次内部分享会上, 偶然知道了这个H5的新事件, 解决了我之前的一个bug. 事情是这样的, 第A网页上显示的数量的总和, 点击去是B页面, 可以进行管理, 增加或者删除, 当用户做了增删操作 ...

  4. taro 学习资料

    taro 学习资料 学习资料 网址 github https://github.com/NervJS/taro taro 官方文档 https://nervjs.github.io/taro/docs ...

  5. RedHat7.3创建本地yum源

    [root@master ~]# mkdir -p /var/www/html 使用安装系统的ISO镜像文件rhel-server-7.3-x86_64-dvd.iso 把rhel-server-7. ...

  6. Android adb 模拟滑动 按键 点击事件

    模拟事件全部是通过input命令来实现的,首先看一下input命令的使用: usage: input ... input text <string>       input keyeven ...

  7. linux 添加多个网段

    1.在系统中添加网络配置文件脚本 # cd /etc/sysconfig/network-scripts # cp ifcfg-eth0 ifcfg-eth0:0 2.修改新添加的网络配置脚本文件如下 ...

  8. 打开word文档总是自动弹出控件工具条的解决办法:

    打开word文档总是自动弹出控件工具条的解决办法:1.查看是否word文档和模板中了'apmp宏病毒,按ALT+F11组合键,双击当前文档下属的ThisDocument,清空里面的内容:双击Norma ...

  9. Windows 使用windump进行循环抓包

    准备工作 1.下载tcpdump http://www.winpcap.org/windump/  2.下载WinPcaphttp://www.winpcap.org/install/bin/WinP ...

  10. 使用mongo shell转换字符类型

    MongoDB数据类型如下: 类型 对应数字 别名 说明 Double1 1 double   String 2 string   Object 3 object   Array 4 array   ...