[英]Trouble enabling OData v4.0 routing in ASP.NET Web API 2.2
[英]OData v4.0 - Change value to results
我目前正在编写API,但是这次,客户端是第3方。 幸运的是,有据可查,但我有1个特殊问题。 客户期望这样的json:
{ "results":[ { "Id":"2C9E76EF-2532-4CA5-B4C6-03E39A31867A", "Code":1, "Name":"Optimizers B.V.", "VatCode":"96541122", "ChamberOfCommerceCode":"28084551", "LanguageCode":"NL", "Discount":2.35, "CustomerManager":"Robin van Halen", "PriceList":"7208812F-EEDA-4345-B3C6-1F1A960558C1", "PaymentCondition":"7BA77586-3A3A-4D07-8DB8-2188F48BD68A", "VatLiable":true }}
我正在使用OData,因为需要将OData用于可查询的选项。 但是,我的结果集却大不相同:
{
"@odata.context": "http://localhost:52973/odata/$metadata#Customers",
"value": [ { "Id":"2C9E76EF-2532-4CA5-B4C6-03E39A31867A", "Code":1, "Name":"Optimizers B.V.", "VatCode":"96541122", "ChamberOfCommerceCode":"28084551", "LanguageCode":"NL", "Discount":2.35, "CustomerManager":"Robin van Halen", "PriceList":"7208812F-EEDA-4345-B3C6-1F1A960558C1", "PaymentCondition":"7BA77586-3A3A-4D07-8DB8-2188F48BD68A", "VatLiable":true }}
区别是
"@odata.context": "http://localhost:52973/odata/$metadata#Customers",
"value": [ ....
我在支持时问了这个问题,他们回答说,我需要将结果的值更改为使其起作用。.但是,我该如何更改呢? 我不太确定该怎么做。
我已经尝试过一些肮脏的骇客,例如:
public IQueryable<Customer> Get()
{
var AllCusts = GetAllCustomers(); //this is of type IQueryable
//Test in order to change value to results
var x = JsonConvert.SerializeObject(AllCusts, Formatting.Indented);
var xyz = JsonConvert.DeserializeObject<List<Customer>>(x.Replace("value", "Results"));
var asQuery = xyz.AsQueryable();
return asQuery;
}
但不幸的是,结果集仍然相同。
为了使其他人由于某种原因不得不重命名值,这是我设法做到的:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Add middleware before MVC
app.Use(async (ctx, next) =>
{
// Capture the original response body stream
var responseStream = ctx.Response.Body;
// Replace it with our own, so that we can read it
using (var bodyStream = new MemoryStream())
{
ctx.Response.Body = bodyStream;
// Run ASP.NET MVC (ie. get the results back from your code)
await next();
// Put the original response body stream back
ctx.Response.Body = responseStream;
// Read the one that we captured
bodyStream.Seek(0, SeekOrigin.Begin);
var responseBody = await new StreamReader(bodyStream).ReadToEndAsync();
// If it's ODATA & JSON & 200 (success), replace the "value" with "results"
if (ctx.Response.ContentType.Contains("application/json") && ctx.Response.ContentType.Contains("odata") && ctx.Response.StatusCode == 200)
{
responseBody = responseBody.Replace("\"value\"", "\"results\"");
}
// Write back the response body (whether modified or not) to the original response stream
await ctx.Response.WriteAsync(responseBody);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.