. NET 5 WebAPI + OData -自定义结果模型



我是否能够使用自定义模型/类使此更整洁?

"@odata.context": "https://localhost:5001/api/$metadata#Customers",
"@odata.count": 4830,
"value": [
{
"Id": 1,
"Code": "",
"Name1": "",
"Name2": "",
"Name3": ""
},
...

我不需要@data.context,我希望能够为零结果添加响应消息。

例如:

"responseMessage": "Example message from API with OData",
"responseCode": 10,
"itemsLength": 4830,
"items": [
{
"Id": 1,
"Code": "",
"Name1": "",
"Name2": "",
"Name3": ""
},
...

我还想用相同的模型处理异常

例如:

"responseMessage": "[Exception.Message] - Exception message example text.",
"responseCode": -1,
"itemsLength": 0,
"items": []

我找到解决办法了。

OData最适合EF,因为它"强制";用IQueryable代替IEnumerable。在我的情况下,我不能使用EF,因为它不是我的数据库,所以我使用Dapper。我们都知道Dapper遵循不同的法律,IQueryable不提供任何好处,但由于这一点,可以使用OData:

返回自定义响应:

public class CustomersResponse
{
public string ReponseMessage { get; set; }
public int ResponseCode { get; set; }
public int ItemsLength { get; set; }
public IQueryable Items { get; set; }
}

KONTROLER

[HttpGet]
public async Task<IActionResult> Get(ODataQueryOptions<Customer> options)
{
var response = new CustomersResponse();
try
{
var customers = await _dataReader.GetCustomers("database_name");
var customersResult = options.ApplyTo(customers.AsQueryable()).Cast<Customer>();
if(customersResult.Count() == 0)
{
response.ItemsLength = customers.Count();
response.ReponseMessage = "NotFound";
response.ResponseCode = 404;
response.Items = customersResult;
return NotFound(response);
}
response.ItemsLength = customers.Count();
response.ReponseMessage = "OK";
response.ResponseCode = 200;
response.Items = customersResult;
return Ok(response);
}
catch (Exception ex)
{
response.ResponseCode = 500;
response.Items = null;
response.ReponseMessage = ex.Message;
response.ItemsLength = 0;
return StatusCode(500, response);
}
}

我们从端点中删除[EnableQuery]属性,添加ODataQueryOptions<Customer> options参数并使用options.ApplyTo(),它将相应地准备数据。我想提醒您,这是平均效率,因为我们收集第一行的所有客户,然后我们使用OData进行过滤。

.Filter()
.OrderBy()
.SetMaxTop(50)
<<p>不工作/strong>
.Count() // we don't need that anymore
.Expand()
.Select()

Select()的情况下,返回的数据很可能有问题,因为OData试图以某种方式将其转换为它的类型。

{
"reponseMessage": "Unable to cast object of type 'Microsoft.AspNetCore.OData.Query.Wrapper.SelectSome`1[OptimoLogic.Models.Customer]' to type 'OptimoLogic.Models.Customer'.",
"responseCode": 500,
"itemsLength": 0,
"items": null
}

最新更新