【问题标题】:ASP.NET MVC4 Web API MediaTypeFormatter Converter to convert XElement to JSONASP.NET MVC4 Web API MediaTypeFormatter 转换器将 XElement 转换为 JSON
【发布时间】:2012-03-23 14:26:04
【问题描述】:

我正在 ASP.NET MVC4 Web API 中构建一个 API,我的一个操作返回 XML(当前为 XElement 的形式)。我无法控制数据,我只是在传递它。没有可以将其反序列化为的标准对象。

public Task<XElement> Get( string queryName, string query )...

如果需要,我想要做的是使用 MediaTypeFormatter 将其转换为 JSON。我已经开始编写 MediaTypeFormatter 并将其连接起来,但是当我在控制器上调用“Get”时,它会调用

protected override bool CanWriteType( Type type )
{
    return true;
}

在 MediaTypeFormatter 中,但永远不会达到 OnWriteToStreamAsync 方法。结果只是作为字符串的 XML,例如

"<testXmlHere\/>"

有人知道如何解决这个问题吗?

谢谢

【问题讨论】:

  • 为什么你的 API 返回一个任务?
  • 这样做是为了启用异步执行。上面有很多文章,但几乎整个堆栈都是为异步执行而设计的。

标签: c# xml json asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您的自定义格式化程序可能插入到格式化程序集合中 JsonMediaTypeFormatter 之后的格式化程序列表中。该格式化程序可以编写 XElement,并且通过将 XML 表示形式编写为 JSON 字符串来实现(这是一个好主意还是坏主意是另一个讨论)。将格式化程序添加到集合时,请使用 Insert 而不是 Add 方法:

GlobalConfiguration.Configuration.Formatters.Insert(
    0, new MyCustomMediaTypeFormatter());

【讨论】:

    【解决方案2】:

    这是一个疯狂的建议...首先创建一个 HttpResonponse 消息并将内容设置为您要检索的任何数据。尝试创建自定义操作过滤器 (System.Web.HttpFilters.ActionFilterAttribute) 并实现 OnActionExecuted 方法。

    在您的方法中,从 HttpActionExecutedContext 获取相应的 HttpRequest 和 HttpResponse 对象。您可以从 HttpRequest 中检索 Accept 标头,并从 HttpResponse 中检索您的数据。如有必要,根据请求的 Accept 标头格式化您的数据,并将其重新分配给 Response 内容。

    你知道我从哪里来吗??

    【讨论】:

      【解决方案3】:
          public HttpResponseMessage<SensorUpdate> Post(int id)
          {
              SensorUpdate su = new SensorUpdate();
              su.Id = 12345;            
              su.Username = "SensorUpdateUsername";
              su.Text = "SensorUpdateText";
              su.Published = DateTime.Now;
      
      
              HttpResponseMessage<SensorUpdate> response = new HttpResponseMessage<SensorUpdate>(su, 
                          new MediaTypeHeaderValue("application/json"));
      
              return response;
          }
      

      【讨论】:

      • 仅供参考 - HttpResponseMessage 对象已被弃用
      【解决方案4】:

      MVC4 快速提示 #3 – 从 ASP.Net Web API 中删除 XML 格式化程序

      在 Global.asax 中: 添加行:

      GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
      

      像这样:

              protected void Application_Start()
          {
              AreaRegistration.RegisterAllAreas();
      
              RegisterGlobalFilters(GlobalFilters.Filters);
              RegisterRoutes(RouteTable.Routes);
      
              BundleTable.Bundles.RegisterTemplateBundles();
              GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-01
        • 2013-10-24
        • 2014-09-05
        • 2012-10-04
        • 2013-02-05
        • 2011-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多