如何解决Odata .Net Core v4 MVC路由不起作用
学习Odata时,我尝试了一个带有书的测试项目,然后尝试在连接数据库的情况下制作自己的书。这两个项目都具有edmx版本4,并且配置类似。
但是,当在原始项目中使用参数调用我的方法时,它不起作用,但在Book示例中可以。等等odata / v4 / Resources(1)比books(1)。我可以从“公司”和资源控制器中获取数据,但不能从AccountController中获取数据,即使这是明智的类似设置方法。它返回404 not found。我可以在资源控制器上执行?$ select过滤,但不能在companiesController上执行。其他所有odata函数均应正常工作。更改为odataprefix和odataroute后,每个控制器都可以工作,但是带有参数的方法调用不起作用。
我不知道自己缺少什么或什么给了我这个问题,现在正在寻求帮助。
我一直关注并阅读的指南在下面链接。我知道前缀路由是不同的,但是它应该像书测试中那样开始工作:
亲切的问候
Start.cs-我的项目-Github => original project
enter code here
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//-- Own data - This is entity framework core without
services.AddDbContext<CompanyBrokerEntities>(options => options.UseSqlServer(Configuration.GetConnectionString("CompanyBrokerEntities")));
//--- Adding odata to asp.net core's dependency injection system
services.AddOData();
//--- ODATA CONTENT ROUTE disabling - Odata does not support end point routing
services.AddMvc(mvcOptions => mvcOptions.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//--- ODATA CONTENT ROUTE for each controller with 'odata' infront of it
app.UseMvc(routebuilder =>
{
// EnableDependencyInjection is required if we want to have OData routes and custom routes together in a controller
routebuilder.EnableDependencyInjection();
//- The route etc. localhost:50359/odata/v4/Accounts
//- sets the route name,prefix and Odata data model
routebuilder.MapODataServiceRoute("ODataRoute","odata/v4",GetEdmModel());
//-- enables all OData query options,for example $filter,$orderby,$expand,etc.
routebuilder.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
});
}
////--- ODATA CONTENT - Create the OData IEdmModel as required:
private IEdmModel GetEdmModel()
{
//-- Creates the builder
var odataBuilder = new ODataConventionModelBuilder();
//-- Eks odataBuilder.EntitySet<ResourceDescription>("Resource Descriptions").EntityType.HasKey(p => p.DescriptionId);
//-- Use Annotations with [Key] field on the primary key fields in the model instead of above one liner
odataBuilder.EntitySet<CompanyAccount>("Accounts");
odataBuilder.EntitySet<Company>("Companies");
odataBuilder.EntitySet<CompanyResource>("Resources");
odataBuilder.EntitySet<ResourceDescription>("Descriptions");
//var getAccountF = odataBuilder.EntityType<CompanyAccount>().Function("GetAccount");
// getAccountF.Returns<AccountResponse>();
// getAccountF.Parameter<string>("username");
//var GetResourcesByIdF = odataBuilder.EntityType<CompanyResource>().Function("GetResourcesByCompanyId");
// GetResourcesByIdF.ReturnsCollection<IList<CompanyResource>>();
// GetResourcesByIdF.Parameter<int>("companyId");
//-- returns the IEdmModel
return odataBuilder.GetEdmModel();
}
}
帐户管理员
//[ODataRoutePrefix("Accounts")]
public class AccountController : ODataController
{
#region constructor and DBS data
//-- database context
private readonly CompanyBrokerEntities db;
public AccountController(CompanyBrokerEntities context)
{
db = context;
}
#endregion
#region Get Methods
/// <summary>
/// Fetches all accounts,through a model to not contain sensitive data like passwords.
/// </summary>
/// <returns></returns>
[EnableQuery]
//[ODataRoute]
public async Task<IActionResult> GetAccounts()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//-- Uses the CompanyBrokeraccountEntity to access the database
//-- Filtered by AccountResponse for sensitive data
var responseList = await db.CompanyAccounts.AsQueryable().Select(a => new AccountResponse(a)).ToListAsync();
if (responseList != null)
{
return Ok(responseList);
}
else
{
return NotFound();
}
}
上下文-使用EF创建的DBS数据集
public partial class CompanyBrokerEntities : DbContext
{
public virtual DbSet<Company> Companies { get; set; }
public virtual DbSet<CompanyAccount> CompanyAccounts { get; set; }
public virtual DbSet<CompanyResource> CompanyResources { get; set; }
public virtual DbSet<ResourceDescription> ResourceDescriptions { get; set; }
//public CompanyBrokerEntities() : base("name=CompanyBrokerEntities")
//{
//}
//protected override void OnModelCreating(DbModelBuilder modelBuilder)
//{
// throw new UnintentionalCodeFirstException();
//}
public CompanyBrokerEntities(DbContextOptions<CompanyBrokerEntities> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//throw new UnintentionalCodeFirstException();
}
}
书本测试:Github => test project
start.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//---- ODATA CONTENT
services.AddOData();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddDbContext<BookStoreContext>(opt => opt.UseInMemoryDatabase("BookLists"));
services.AddMvc(options => options.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//--- ODATA CONTENT ROUTE
app.UseMvc(b =>
{
//- The route
b.MapODataServiceRoute("odata","odata",GetEdmModel());
//-- Adding the following line of code in Startup.cs enables all OData query options,etc.
b.Select().Expand().Filter().OrderBy().MaxTop(100).Count();
});
}
//--- ODATA CONTENT
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Book>("Books");
builder.EntitySet<Press>("Presses");
return builder.GetEdmModel();
}
BookController
public class BooksController : ODataController
{
private BookStoreContext _db;
public BooksController(BookStoreContext context)
{
_db = context;
if (context.Books.Count() == 0)
{
foreach (var b in DataSource.GetBooks())
{
context.Books.Add(b);
context.Presses.Add(b.Press);
}
context.SaveChanges();
}
}
// ...
[EnableQuery]
public IActionResult Get()
{
return Ok(_db.Books);
}
[EnableQuery]
public IActionResult Get([FromODataUri] int key)
{
return Ok(_db.Books.FirstOrDefault(c => c.Id == key));
}
// ...
[EnableQuery]
public IActionResult Post([FromBody] Book book)
{
_db.Books.Add(book);
_db.SaveChanges();
return Created(book);
}
}
解决方法
- 调用 odata / v4 / Accounts 时的404是因为将您的实体集命名为
Accounts
,而将控制器命名为AccountCoutroller
。设为AccountsController
,它将处理404 - 关于在 / odata / v4 / Resources 上有效的查询选项($ filter,$ select等),在 / odata / v4 / Companies 上无效的查询选项,请注意,
GetCompanies
操作将返回CompanyResponse
(而非Company
)个对象。CompanyResponse
未在服务元数据中表示-在EDM中未显示。您实际上看到的响应是因为您的API依赖于ASP.NET Web API序列化。 OData在构造$ filter或$ select表达式时会遇到挑战,因为它对CompanyResponse
一无所知。返回Company
对象将解决此问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。