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

本文介绍如何使ASP.NET WebAPI在不使用OData的情况下支持$format参数,通过简单配置即可让API响应特定格式如JSON或XML,便于前端调用与测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文转自: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

作者:BobLiu 邮箱:lzd_ren@hotmail.com 出处:http://www.cnblogs.com/liuzhendong 本文版权归作者所有,欢迎转载,未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值