让ASP.NET Web API支持$format参数的方法

在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可: 

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

namespace ProjectManagementWebAppV4
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
            config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
        }
    }
}

首先是:using System.Net.Http.Formatting; 其实就是System.Net.Http.Formatting.dll。

然后是:config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
            config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"
);

JsonMediaTypeFormatter和XmlMediaTypeFormatter是两个起实际作用的Media格式化器,用于序列化和反序列化HTTP请求及响应,给它们添加了$format参数之后就大功告成了!

这样,无论是在IE中,还是在chrome中,只要在url后面添加$format=json或$format=xml参数,浏览器就可以返回相应格式的数据了,也不必改Http请求Header中的Accept媒体类型了,这样测试WebAPI时更方便了。

URL如下:

http://localhost:port/api/ProjectManagent?$format=json

http://localhost:port/api/ProjectManagent?$format=xml

 

Demo源代码下载: 原代码下载

参考资料:https://code.msdn.microsoft.com/Support-format-in-ASPNET-e3785b2a

posted on 2015-01-16 14:13  BobLiu  阅读(1933)  评论(0编辑  收藏  举报