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

   }
相关推荐
阿华的代码王国12 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
DavieLau2 天前
C#项目WCF接口暴露调用及SOAP接口请求测试(Python版)
xml·服务器·开发语言·python·c#
曹牧2 天前
XML头部声明发送者信息的实现方法
xml
寒士obj3 天前
熟悉并使用Spring框架 - XML篇
xml·java·spring
Arva .3 天前
Spring基于XML的自动装配
xml·java·spring
fatfishccc4 天前
循序渐进学 Spring (上):从 IoC/DI 核心原理到 XML 配置实战
xml·java·数据库·spring·intellij-idea·ioc·di
fatfishccc8 天前
【MyBatis新手避坑】详解 `Could not find resource ...Mapper.xml` 错误
xml·intellij-idea·mybatis
helloworld工程师8 天前
Dubbo应用开发之基于xml的第一个Dubbo程序
xml·dubbo·safari
coding随想10 天前
DOM的XML命名空间革命:从混乱到有序的蜕变
xml
真实的菜10 天前
MyBatis核心配置深度解析:从XML到映射的完整技术指南
xml·tomcat·mybatis