OData WebAPI 2 - 属性方法返回xml而不是json

时间:2013-12-01 13:39:16

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

我正在使用OData WebAPI 2。 所有动作(获取实体集,通过id获取实体......)返回json 当我试图获取导航属性时,它返回预期的json响应。 但是当我试图获取属性时,响应是xml,这是不期望的。

这是我的控制器代码:

    /// <summary>
    /// Gets the navigation property.
    /// </summary>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public virtual HttpResponseMessage GetNavigationProperty([FromODataUri] string key) {
        ODataPath oDataPath = this.Request.GetODataPath();
        var navigationPropertyName = (oDataPath.Segments[2] as NavigationPathSegment).NavigationPropertyName;
        return GetProperty(key, navigationPropertyName);
    }

    /// <summary>
    /// Gets the property.
    /// </summary>
    /// <returns></returns>
    public virtual HttpResponseMessage GetProperty() {
        ODataPath oDataPath = this.Request.GetODataPath();
        var propertyName = (oDataPath.Segments[2] as PropertyAccessPathSegment).PropertyName;
        var key = (oDataPath.Segments[1] as KeyValuePathSegment).Value;
        return GetProperty(key, propertyName);
    }

    private HttpResponseMessage GetProperty(string key, string propertyName) {
        var entity = GetEntities(key, new[] { propertyName }).FirstOrDefault();
        var content = typeof(TEntity).GetProperty(propertyName).GetValue(entity, null);

        // There are two System.Net.Http.HttpRequestMessageExtensions classes in two different dlls, we want the one on System.Web.Http.dll
        var assembly = AppDomain.CurrentDomain.GetAssemblies().First(x => x.FullName.StartsWith("System.Web.Http,"));
        var type = assembly.GetType("System.Net.Http.HttpRequestMessageExtensions");
        // Method with parameter T, can't get it via GetMethod so we look it up as the only CreateResponse with 3 parameters.
        MethodInfo method = type.GetMethods().First(x => x.Name == "CreateResponse" && x.GetParameters().Length == 3);
        MethodInfo generic = method.MakeGenericMethod(content.GetType());
        var response = generic.Invoke(Request, new[] { Request, HttpStatusCode.OK, content });

        // Return our response.
        return response as HttpResponseMessage;
    }

我有什么问题吗? 谢谢! 欧米。

1 个答案:

答案 0 :(得分:2)

这是预期的,因为大多数浏览器在其接受标头中都有application / xml。例如,chrome发送此

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

OData协议将实体和实体集合指定为application/atom+xml,将属性(复杂,原始,复杂集合,原始集合)指定为application/xml。以上所有内容都可以并将在世界的json方面格式化为application/json

当您从浏览器请求实体或订阅源时,上述接受标题中没有内容类型可以根据OData规范格式化实体/订阅源。因此,我们默认为application/json。但是,如果您要求提供属性(非导航),则application/xml的Accept标头中会有匹配项。因此,我们发回application/xml