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);
    }
}

解决方法

  1. 调用 odata / v4 / Accounts 时的404是因为将您的实体集命名为Accounts,而将控制器命名为AccountCoutroller。设为AccountsController,它将处理404
  2. 关于在 / odata / v4 / Resources 上有效的查询选项($ filter,$ select等),在 / odata / v4 / Companies 上无效的查询选项,请注意,GetCompanies操作将返回CompanyResponse(而非Company)个对象。 CompanyResponse未在服务元数据中表示-在EDM中未显示。您实际上看到的响应是因为您的API依赖于ASP.NET Web API序列化。 OData在构造$ filter或$ select表达式时会遇到挑战,因为它对CompanyResponse一无所知。返回Company对象将解决此问题。