ASP.NET MVC4 Web API MediaTypeFormatter转换器将XElement转换为JSON

时间:2012-03-06 04:54:39

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

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

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

由于

4 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

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

你到达我来自哪里?

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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