码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2017-05-27 17:59:53      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:template   optional   ram   post   web api   cat   generic   app   格式化   

本文转自:http://www.cnblogs.com/liuzhendong/p/4228592.html

在不使用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

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

标签:template   optional   ram   post   web api   cat   generic   app   格式化   

原文地址:http://www.cnblogs.com/freeliver54/p/6913834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!