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

   }
相关推荐
那个失眠的夜1 天前
Mybatis延迟加载策略
xml·java·数据库·maven·mybatis
mfxcyh1 天前
基于xml、注解、JavaConfig实现spring的ioc
xml·java·spring
vortex51 天前
SOAP 协议中的 XML 外部实体注入(XXE)漏洞
xml·网络安全·渗透测试
Dxy12393102161 天前
Python如何对XML进行格式化
xml·python
2501_930707782 天前
使用C#代码将 HTML 转换为 PDF、XPS 和 XML
xml·pdf
研來如此7 天前
tinyxml2 常用读取接口对照表
xml·c++·tinyxml2
pupudawang8 天前
使用 Logback 的最佳实践:`logback.xml` 与 `logback-spring.xml` 的区别与用法
xml·spring·logback
jf加菲猫8 天前
第10章 数据处理
xml·开发语言·数据库·c++·qt·ui
Java成神之路-8 天前
序列化协议全解析:XML、SOAP、JSON 与 Protobuf 实战对比及 Protobuf 演进方案
xml·json
帅次8 天前
WebView 并发初始化竞争风险分析
android·xml·flutter·kotlin·webview·androidx·dalvik