zoukankan      html  css  js  c++  java
  • [转]让ASP.NET Web API支持$format参数的方法

    本文转自: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 本文版权归作者所有,欢迎转载,未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    创建对象的模式
    linux下安装node v12.16.3
    es6知识点总结
    在阿里云上部署的node服务器不能通过公网IP访问
    angular 1 input中选中状态绑定
    让一个元素水平垂直居中
    语录收集
    跨域
    事件循环
    git的常用命令
  • 原文地址:https://www.cnblogs.com/freeliver54/p/6913834.html
Copyright © 2011-2022 走看看