Fal*_*con 4 c# asp.net api odata asp.net-core
对 ASP.Net Core 来说很新,特别是对于 API。过去,我习惯于使用默认控制器创建简单的 api,例如:
[Produces("application/json")]
[Route("api/TestCust")]
public class TestCustController : Controller
{
// GET: api/TestCust
[HttpGet]
public IEnumerable<Customer> Get()
{
IEnumerable<Customer> customer = null;
....
return customer;
}
// GET: api/TestCust/5
[HttpGet("{id}", Name = "Get")]
public IEnumerable<Customer> Get(int id)
{
IEnumerable<Customer> customer = null;
return customer;
}
Run Code Online (Sandbox Code Playgroud)
现在我在制作 API 时遇到了新的挑战,但客户端已经由第三方制作。这意味着,我被迫按照他们的方式去做。
幸运的是,它有很好的文档记录,并且他们提供了将发送到我的 API 的请求示例。其中一个请求如下:/Customers?$filter=ID+eq+guid'1D225D75-A587-4AE4-BA9A-2224B2484EA5'
为了获得所有客户: /Customers?$orderby=Code&$skip=100
现在,我对 OData 完全陌生,我昨天才发现这些,并且我一直在关注有关它的一些教程。虽然,他们中的大多数都使用实体框架,而我将 Dapper 与存储过程结合使用。
教程如下:https : //damienbod.com/2018/10/12/odata-with-asp-net-core/,https : //dotnetthoughts.net/perform-crud-operations-using-odata-in-aspnet-核/
所以我一直在尝试使用 提出请求, [EnableQuery]
但这还没有奏效。我将链接底部的错误。
那么,我到底做了什么?好吧,我更改了Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddOData();
services.AddODataQueryFilter()
services.AddMvc();
services.AddOptions();
}
Run Code Online (Sandbox Code Playgroud)
在我的客户控制器中:
public class CustomersController : ODataController{
...
[EnableQuery]
public IEnumerable<Customer> Get()
{
IEnumerable<Customer> allCustomers = null;
IEnumerable<Addresses> allAddresses = null;
IEnumerable<Contacts> allContacts = null;
//Execute the procedures to fetch our objects.
using (var connection = new SqlConnection(config.Value.ConnectionString.ToString()))
{
allCustomers = connection.Query<Customer>("someproc");
allAddresses = connection.Query<Addresses>("someproc");
allContacts = connection.Query<Contacts>("someproc");
}
//Loop through our customer object
foreach(var item in allCustomers)
{
//Initialize a collection of address + contact
ICollection<Contacts> CustomerContact = null;
ICollection<Addresses> CustomerAddress = null;
//Bind the Contact and Address to the correct Customer using the CustomerID
//Tijdelijk uitgezet omdat customer nu even geen GUID is..
//CustomerContact = allContacts.Where(x => x.Customer == item.Id).ToList();
//CustomerAddress = allAddresses.Where(x => x.Customer == item.Id).ToList();
item.Contacts = CustomerContact;
item.Addresses = CustomerAddress;
}
return allCustomers;
}
Run Code Online (Sandbox Code Playgroud)
这是它在浏览器/邮递员中作为“错误 400 错误请求”返回的消息:
URI 中指定的查询无效。找不到非 OData 路由的服务容器。在非 OData 路由上使用 OData 组件时可能会发生这种情况,并且通常是配置问题。调用 EnableDependencyInjection() 以在非 OData 路由上启用 OData 组件。当请求被 ASP.NET Core 路由层而不是 OData 路由层错误处理时,也可能发生这种情况,例如 URL 不包含通过调用 MapODataServiceRoute() 配置的 OData 路由前缀
这里有几件事。首先,要使用 OData,您需要返回 IQueryable,而不是 IEnumerable。另外,我不确定 Dapper 是否适用于 OData,因为 OData 是一种 MS 技术,主要设计用于与 EF 和“实体”一起使用。我认为您可能能够让它工作,但您需要将某种解决方案组合在一起,这些解决方案采用 ODataQueryOptions 输入并将它们映射到 EF 端的 IQueryable。(基本上,这并不容易)
归档时间: |
|
查看次数: |
2931 次 |
最近记录: |