问:c#webapi核心2.0路由与odata v4.0?

时间:2018-01-24 09:50:45

标签: asp.net-web-api2 odata asp.net-core-2.0 .net-core-2.0

目前我使用webapi和odata并希望创建一个小型测试项目。路由映射当前无法正常工作。

我使用以下libs: - Microsoft.AspNetCore.All(2.0.3) - Microsoft.AspNetCore.Odata(7.0.0-beta1) - 最新的带有core2.0的webapi

配置部分:

return fetch<User>('https://...').then(getData);

控制器部分:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    //Adding Model class to OData
    var builder = new ODataConventionModelBuilder(app.ApplicationServices);
    builder.EntitySet<Person>($"{nameof(Person)}s");

    //app.
    //app.UseMvcWithDefaultRoute();
    app.UseMvc(routebuilder =>
    {
        routebuilder.EnableDependencyInjection();
        routebuilder.Filter().Expand().Select().OrderBy().MaxTop(null).Count();
        routebuilder.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
    });
}

模型部分:

public class PersonsController : ODataController
{
    private static readonly List<Person> myPersons = new List<Person>
    {
        new Person {Firstname = "Person1", Lastname= "Test", Id = "p1"},
        new Person {Firstname = "Person2", Lastname= "Test", Id = "p2"},
        new Person {Firstname= "Person3", Lastname= "Test", Id = "p3"},
        new Person {Firstname= "Person4", Lastname= "Test", Id = "p4"},
    };

    public IQueryable<Person> GetPersons()
    {
        return myPersons.AsQueryable();
    }

    public Person GetPerson([FromODataUri] string key)
    {
        return myPersons.FirstOrDefault(x => x.Id == key);
    }
}

the odata documentation中,这些调用现在应该有效:

  • 〜/ OData的/人
  • 〜/ OData的/人( 'P1')

但他们不是。我总是从IIS中找到一个找不到页面的页面。我认为MapODataServiceRoute调用没有正确设置路由。 Î不要使用webapi中的任何默认路由。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我尝试了几件事,找到了问题的解决方案。 配置方法中的顺序很重要:

这是有效的:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddOData();
}

这不是:

public void ConfigureServices(IServiceCollection services)
{
    services.AddOData();
    services.AddMvc();
}
相关问题