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 天前
批量格式化XML与JSON文件小工具
xml·json
还算善良_3 天前
XML签名
xml·java·开发语言
梅梅绵绵冰3 天前
xml方式实现AOP
xml·java·开发语言
一条晓鱼5 天前
repo xml语法
xml
萝卜白菜。6 天前
关于Java EE应用中xml解析类的问题
xml·java·java-ee
ejinxian7 天前
protobuf 、JSON、XML传输格式
xml·json·protobuf
yue0088 天前
C# XML文件的读写V2.0
xml·开发语言·c#
emma羊羊9 天前
【weblogic】XML反序列化漏洞
xml·安全
研來如此11 天前
XML与HTML
xml·html
一个W牛11 天前
报文比对工具(xml和sop)
xml·前端·javascript