C#中的WebApi响应Accept头,自动返回xml或者json

Global.asax.cs中的Application_Start方法添加

GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new XmlMediaTypeFormatter()); GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

默认就有4个Formatter。不需要添加

.net core写在public void ConfigureServices(IServiceCollection services) 方法中

builder.Services.AddControllers(op => { op.RespectBrowserAcceptHeader = true; }).AddXmlSerializerFormatters();

postman参考:

如果使用Dynamic类型,需要添加xmlInClude来指定序列化的类

cs 复制代码
 await Task.Run(new Action(() =>
 {
     response.data = _db.Database.SqlQueryRaw<OutputEntityM>(sql).FirstOrDefault();

 }));
cs 复制代码
   [XmlInclude(typeof(OutputEntityC))]
   [XmlInclude(typeof(OutputEntityM))]
   public class ResponseEntity
   {
       public string flag { get; set; }
       public string message { get; set; }
      
       public dynamic data { get; set; }

   }
相关推荐
gAlAxy...9 小时前
MyBatis 核心配置文件 SqlMapConfig.xml 全解析
xml·mybatis
编程修仙1 天前
第十一篇 Spring事务
xml·java·数据库·spring
金士顿1 天前
Ethercat耦合器添加的IO导出xml 初始化IO参数
android·xml·java
烤麻辣烫2 天前
黑马程序员苍穹外卖后端概览
xml·java·数据库·spring·intellij-idea
暗碳2 天前
安卓abx二进制xml文件转换普通xml文件
android·xml
jinxinyuuuus2 天前
文件格式转换工具:XLSX的XML流式解析、数据类型推断与CSV编码规范
xml
czlczl200209252 天前
从抛出异常到返回 JSON/XML:SpringBoot 异常处理全链路解析
xml·spring boot·json
jiayong233 天前
MyBatis XML Mapper 特殊字符处理方案
xml·mybatis
e***19353 天前
【mybatis】基本操作:详解Spring通过注解和XML的方式来操作mybatis
xml·spring·mybatis
编程修仙3 天前
第七篇 java的注解以及使用反射实现自定义注解功能
xml·java·开发语言·spring