webapi 返回json

web api 默认的已 xml 格式返回数据

现在开发一般都是以 json 格式为主

下面配置让 webapi 默认返回 json ,在需要返回 xml 时只需要加一个查询参数 datatype=xml 即可返回 xml 格式数据

配置如下:

1.新建 一个 mvc webapi 项目 (framework4.0)

2.找到默认的 WebApiConfig.cs 文件

3.修改 WebApiConfig.cs 文件

<span style="font-family: Arial, Helvetica, sans-serif;">using System;</span>
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace MvcWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
	    .......

            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            //默认返回 json
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "json", "application/json"));
            //返回格式选择 datatype 可以替换为任何参数
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "xml", "application/xml"));
        }
    }
}

4.修改默认路由规则 WebApiConfig.cs 文件中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace MvcWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
	    //新加的规则
            config.Routes.MapHttpRoute(
                name: "DefaultApi2",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
	    //新加的规则
            config.Routes.MapHttpRoute(
                name: "DefaultApi1",
                routeTemplate: "api/{controller}/{action}",
                defaults: new { id = RouteParameter.Optional }
            );
	    //默认路由
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
	    。。。。。
        }
    }
}

5.添加测试 action

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MvcWebApi.Controllers
{
    public class ValuesController : ApiController
    {
        /// <summary>
        /// web api 默认将以 get 开头的只支持 get 请求,post 开头的支持支 post 请求
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.HttpGet]
        [System.Web.Http.HttpPost]
        public MyClass GetMyClass()
        {
            return new MyClass()
            {
                id=1111,
                name="张三",
                time=DateTime.Now
            };
        }
    }

    public class MyClass
    {
        public int id { set; get; }
        public string name { set; get; }
        public DateTime time { set; get; }
    }
}

6.测试

请求地址:http://localhost:61667/api/values/getmyclass

响应内容:

{"id":1111,"name":"张三","time":"2015-09-29T16:43:07.4731034+08:00"}

请求地址:http://localhost:61667/api/values/getmyclass?datatype=xml

响应内容:

<MyClass><id>1111</id><name>张三</name><time>2015-09-29T16:43:45.3663004+08:00</time></MyClass>

时间: 2024-08-28 13:46:18

webapi 返回json的相关文章

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

ASP.NET Web API 是新一代的 HTTP 網路服務開發框架,除了可以透過 Visual Studio 2012 快速開發外 (內建於 ASP.NET MVC 4 的 Web API 專案範本內),也非常適合用於各種跨平台的行動裝置上,如果你想開發 RESTful 應用程式,那麼使用 ASP.NET Web API 應該是挺理想的解決方案.不過 ASP.NET Web API 內建支援 JSON 與 XML 兩種輸出格式,並依據瀏覽器端送出的 Accept 標頭自動決定回應的內容格式,

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

因为 Internet Explorer 和 Firefox 发送了不同的 Accept 头,所以 web API 在响应里就发送了不同的内容类型.   解决方法,在 Global.asax的 Application_Start() 加入下面的代码 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();     参考 :http://blog.miniasp.com/post/2

webapi返回json格式优化

一.设置webapi返回json格式 在App_Start下的WebApiConfig的注册函数Register中添加下面这代码 config.Formatters.Remove(config.Formatters.XmlFormatter); 二.设置返回Json键值统一为小写 新建一个类并继承自DefaultContractResolver,重写ResolvePropertyName方法, public class UnderlineSplitContractResolver : Defau

C# WebApi 返回JSON

在默认情况下,当我们新建一个webapi项目,会自动返回XML格式的数据,如果我们想返回JSON的数据,可以设置下面的三种方法. 1. 不用改配置文件,在Controller的方法中,直接返回HttpResponseMessage public HttpResponseMessage ReturnJson() { //初始化测试对象 TestJsonObj t = new TestJsonObj(); t.Name = "alun"; t.Address = "GZ"

WebAPI返回JSON的正确格式

最近打算用WebAPI做服务端接口,返回JSON供ANDROID程序调用,结果试了好几次JSONObject都无法解析返回的JSON字符串.看了一下服务端代码: public string Get() { return "{\"errNum\":300202,\"errMsg\":\"Missing apikey\"}"; } 打开CHROME浏览器,F12查看了一下返回信息,发现返回头Content-Type是"a

C# 去掉webapi返回json所带的转义字符

反序列换报错: {"Error converting value \"{\"Result\":true,\"Code\":\"\",\"Msg\":\"success\",\"Data\":[\"/_temp/Other/png/20190425/20190425173934_7723.png\"]}\" to type 'Abhs.Co

使C# WebApi返回Json

找到Global.asax文件,在Application_Start()方法中添加一句: protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.Re

C#WebAPI返回json去掉双引号前面的反斜杠

string str="{\"msgType\":1001,\"msgstring\":\"信息\"}";//这里是你的json带有反斜杠的 HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "applicati

NetCore偶尔有用篇:NetCore项目WebApi返回Json属性大小写

一.概述 1.前面文章介绍Controller的大小写问题时,目的只是介绍它的差异性,有同学回复了,这里把它作为一个点写一下吧. 二.默认定义的转换结果 1.写一个返回对象的方法. 2.运行查看结果. api方法如下 public class OneController : Controller { public Model GetString(string id) { return new Model() { ID = id, Name = "aa" }; } } public cl