我正在创建一个项目,该项目将使用Angular前端与.net核心Web Api项目进行对话,并使用OData提供丰富的查询。 我已经将OData Nuget软件包添加到我的角度项目中。
我遵循了以下教程: https://devblogs.microsoft.com/odata/simplifying-edm-with-odata/
在我的 Startup.cs
中public void ConfigureServices(IServiceCollection services)
{
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
/* snipped some code about DbContext and AutoMapper, not relevant */
services.AddMvcCore(action => action.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOData();
services.AddODataQueryFilter();
}
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Asset>("Assets");
return builder.GetEdmModel();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.EnableDependencyInjection();
routes.Select().Filter().OrderBy().Expand().Count().MaxTop(10);
routes.MapODataServiceRoute("api", "api", GetEdmModel());
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
在我的 API控制器类(在此称为“资产”)
public class AssetsController : ControllerBase
{
public AssetsController(IAssetService _service)
{
this._service = _service;
}
[HttpGet("[action]")]
[EnableQuery()]
public ActionResult<IEnumerable<Asset>> All()
{
var assets = _service.GetAllAssets();
return assets.ToList();
}
}
问题1
如果我从Web API Controller类中删除了ApiController属性,则URL http://localhost:xxxx/api/Assets/All只会再次呈现我的SPA。
[Route("api/[controller]")]
[ApiController]
问题2
如果我再次将此代码添加到我的班级,则会发生以下情况:
正在调用http://localhost:xxxx/api/Assets?$ count = true 应该返回这样的列表:
{
"@odata.context": "https://localhost:44374/api/$metadata#Assets",
"@odata.count": 2,
"value": [
{
"Id": "9cef40f6-db31-4d4c-997d-8b802156dd4c",
"Name": "Asset 1",
},
{
"Id": "282be5ea-231b-4a59-8250-1247695f16c3",
"Name": "Asset 2",
}
]
}
但是此端点返回:
[
{
"Id": "9cef40f6-db31-4d4c-997d-8b802156dd4c",
"Name": "Asset 1",
},
{
"Id": "282be5ea-231b-4a59-8250-1247695f16c3",
"Name": "Asset 2",
}
]
有人知道发生了什么或我做错了什么吗?
答案 0 :(得分:0)
尝试删除此行:
routes.EnableDependencyInjection();