【发布时间】:2013-12-17 05:48:05
【问题描述】:
我正在使用 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;
}
我做错了什么吗? 谢谢! 暗里。
【问题讨论】:
-
我从未尝试过使用 OData 的 Web API 2,但据我所知,响应格式不是由客户端发送的
Accept标头控制的吗?您是否为该标头指定了application/json? -
据我所知,您是完全正确的。问题是,我没有定义任何具体的东西。刚刚用我的浏览器测试了服务。
标签: c# xml json asp.net-web-api odata