您好,欢迎来到华佗健康网。
搜索
您的当前位置:首页.Net基于MVC4WebApi输出Json格式实例

.Net基于MVC4WebApi输出Json格式实例

来源:华佗健康网
.Net基于MVC4WebApi输出Json格式实例

本⽂实例讲述了.Net基于MVC4 Web Api输出Json格式的⽅法,分享给⼤家供⼤家参考。具体实现⽅法如下:1、Global 中增加json输出

复制代码 代码如下:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping(\"json\\"true\2、Global 中删除xml解析

复制代码 代码如下:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();protected void Application_Start(){

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles);

//删除xml的解析 当返回值是string 时 直接返回string不是json对象

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); }

3、指定返回格式新建⽅法 需要程序集:

复制代码 代码如下:

System.Web.Extensions

public static HttpResponseMessage ToJson(Object obj){

String str;

if (obj is String || obj is Char) {

str = obj.ToString(); } else {

var serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); }

var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding(\"UTF-8\"),\"application/json\") }; return result;}

调⽤户⽅法转换为json对象输出

复制代码 代码如下:

public HttpResponseMessage GetString(string name){

return ToJson(name);}

4、重写默认实现类 所有输出将被重新解析成 json新建JsonContentNegotiator 类

复制代码 代码如下:

public class JsonContentNegotiator : IContentNegotiator{

private readonly JsonMediaTypeFormatter _jsonFormatter;

public JsonContentNegotiator(JsonMediaTypeFormatter formatter) {

_jsonFormatter = formatter; }

public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerableformatters) {

var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue(\"application/json\")); return result; }}

WebApiConfig中使⽤重写

复制代码 代码如下:

public static void Register(HttpConfiguration config){

config.Routes.MapHttpRoute( name: \"DefaultApi\

routeTemplate: \"api/{controller}/{id}\

defaults: new { id = RouteParameter.Optional } );

var jsonFormatter = new JsonMediaTypeFormatter();

config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));希望本⽂所述对⼤家的asp.net程序设计有所帮助。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.com 版权所有 湘ICP备2023021991号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务