我正在从WCF数据服务迁移到Web API odata v4. WCF数据服务确实在引号中对长值进行了serilize:
{
"value":[{
"ID":"4527895973896126465"
},{
"ID":"4527895973896126466"
}]
}
Web API odata不会:
{
"value":[{
"ID":4527895973896126465
},{
"ID":4527895973896126466
}]
}
这意味着我在JavaScript中的JSON.parse期间失去了64位数的精度,因为JavaScript数字只有53位.
WebApi是否有内置机制来将长值作为字符串值处理?我正在考虑IEEE754Compatible标头元素.但这对生成的响应没有影响.我忽略了什么吗?
另一种解决方案是在客户端JSON.parse期间将64位数字解除串行化为字符串值.这可能吗?
最佳答案 最后,我得到了这个工作. OdataLib确实通过IEEE754Compatible参数支持这一点.它检查响应Content-Type标头以查看参数是否存在.
问题是,标头值不会自动被web api框架提升到响应头.你必须自己做.我已经构建了一个ODataController派生类,它将IEEE754Compatible参数修补到响应的Content-Type标头中,如下所示:
public abstract class ODataControllerIEEE754Compatible : ODataController
{
private void PatchResponse(HttpResponseMessage responseMessage)
{
if (responseMessage != null && responseMessage.Content != null)
{
if (this.Request.Content.Headers.GetValues("Content-Type").Any(
h => h.Contains("IEEE754Compatible=true")))
{
responseMessage.Content.Headers.TryAddWithoutValidation(
"Content-Type", "IEEE754Compatible=true");
}
}
}
public override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext, CancellationToken cancellationToken)
{
var response = base.ExecuteAsync(
controllerContext, cancellationToken);
response.Wait(cancellationToken);
PatchResponse(response.Result);
return response;
}
}
现在通过在Content-Type Header中发送IEEE754Compatible = true参数,我收到序列化为JSON字符串的所有长值:
GET http://localhost/some/url HTTP/1.1
OData-Version: 4.0;
Content-Type: application/json;odata.metadata=minimal;IEEE754Compatible=true;charset=utf-8
Cache-Control: no-cache
HTTP/1.1 200 OK
Content-Type: application/json;odata.metadata=minimal;IEEE754Compatible=true
Server: Microsoft-HTTPAPI/2.0
OData-Version: 4.0
{
"@odata.context":"http://localhost/some/url","value":[
{
"ID":"4527895973896126465", ...