ASP.NET MVC4 Web API MediaTypeFormatter转换器,用于将XElement转换为JSO

本文关键字:用于 XElement 转换 JSO 转换器 MVC4 NET Web API MediaTypeFormatter ASP | 更新日期: 2023-09-27 18:26:56

我正在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'/>"

有人知道怎么解决这个问题吗?

感谢

ASP.NET MVC4 Web API MediaTypeFormatter转换器,用于将XElement转换为JSO

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

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

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

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

你知道我是从哪里来的吗??

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

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