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; }

   }
相关推荐
2301_818732062 天前
项目启动报错,错误指向xml 已解决
xml·java·数据库·后端·springboot
csdn2015_3 天前
generatorConfig.xml 配置 Controller、Service 完整教程
xml·mybatis
特立独行的猫a3 天前
从XML到Compose的UI变革:现代(2026)Android开发指南
android·xml·ui·compose·jetpack
spencer_tseng4 天前
Stream not available [SysDictDataMapper.xml]
xml·java
qq_297574675 天前
MySQL迁移到瀚高数据库 常用转换函数对照表(附XML示例,直接复用)
xml·数据库·mysql
好好研究5 天前
SpringBoot整合SpringMVC
xml·java·spring boot·后端·mvc
wstcl7 天前
像asp.net core webapi一样在asp.net frameworks中使用Swagger,方便调试接口
后端·asp.net·swagger·webapi
从此不归路7 天前
Qt5 进阶【12】JSON/XML 数据协议处理:与后端/配置文件的对接
xml·开发语言·c++·qt·json
方芯半导体7 天前
EtherCAT “通信 + 控制“ 的全国产化控制方案,ESC芯片(FCE1323)与国产MCU芯片功能板解析
xml·网络·单片机·嵌入式硬件·网络协议·机器人·自动化
好好研究7 天前
总结SSM设置欢迎页的方式
xml·java·后端·mvc