zoukankan      html  css  js  c++  java
  • ASP.NET Web API 通过参数控制返回类型(JSON|XML)

    一个很实用的技巧,可以在访问web api服务的时候指定返回数据的格式类型,比如 json 或者 xml。

    因为 web api 默认返回的是XML格式,但是现在json 比较流行,同时网上也有其他的全局方式的设置。

    比如:

    在 Global 文件中设置,首先清除其他所有的formatters,然后只保留JsonMediaTypeFormatter。

    configuration.Formatters.Clear();
    configuration.Formatters.Add(new JsonMediaTypeFormatter());

    实现步骤:

    1、在 WebApiConfig 文件中引用:System.Net.Http.Formatting

    2、修改 WebApiConfig 代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http.Formatting; 
    using System.Web.Http;
    
    namespace Caixie.Dispatcher
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API 配置和服务
                config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
                config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); 
    
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controlaler}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }

    3、访问

    http://localhost:31591/api/your-action?$format=json

  • 相关阅读:
    静态包含与动态包含
    REST风格下如何放行静态资源
    java迭代器
    es6之扩展运算符 三个点(...)
    关于Echarts配置项的工作记录
    vscode中vue代码格式化的相关配置
    v-loading
    git中Please enter a commit message to explain why this merge is necessary.
    slot
    slot的使用方法
  • 原文地址:https://www.cnblogs.com/easeyeah/p/web-api-return-json-xml.html
Copyright © 2011-2022 走看看