我有 2 个带有 int PK 的 POCO、类(class)和特征。
我设置了导航属性,以便我可以成功 $expand
像这样:
http://localhost:54321/odata/Lessons?$expand=Traits
http://localhost:54321/odata/Traits?$expand=Lessons
我将项目从 Net 461 迁移到 .Net Core 2 的最后一个障碍是 Creating Relationships .
具体来说,当我尝试调用以下方法时,通过以下请求,我得到 404。
[AcceptVerbs("POST", "PUT")]
public async Task<IActionResult> CreateRef(
[FromODataUri] int key, string navigationProperty, [FromBody] Uri link)
{
.... Do Work
}
postman 要求:
http://localhost:54321/odata/Lessons(1)/Traits/$ref
body :
{
"@odata.id":"http://localhost:54321/OData/traits(1)"
}
以下是我的
Startup.Configure
方法。public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
var builder = ConfigureOdataBuilder(app);
app.UseMvc(routeBuilder =>
{
routeBuilder.Select().Expand().Filter().OrderBy().MaxTop(null).Count();
routeBuilder.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
// Work-around for #1175
routeBuilder.EnableDependencyInjection();
routeBuilder.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); // enable mvc controllers
});
}
private ODataConventionModelBuilder ConfigureOdataBuilder(IApplicationBuilder app)
{
var builder = new ODataConventionModelBuilder(app.ApplicationServices);
builder.EntitySet<Lessons>(nameof(Lessons));
builder.EntitySet<Traits>(nameof(Traits));
return builder;
}
问题:我如何达到这个 Controller 方法?
我尝试过的事情,
here .
[ODataRoute("Lessons({key})/{navigationProperty}")]
明确定义路由最佳答案
走了很长一段路,但我终于找到了答案。
[ODataRoute("lessons({lessonId})/traits({traitId})/$ref")]
public IActionResult CreateRef([FromODataUri] int lessonId, [FromODataUri] int traitId)
{
//do work
}
重要提示:您必须像我一样调用 id-params。不要只称他们为 Id - 否则你会得到 404。
还有一件事...
对于那些从 microsoft docs 中尝试过方法的人 - Api-Names 已更改.. 您不需要它们来完成此任务,但如果您必须将 Uri 转换为 OData-Path,这里有一个 Uri-Extension 执行此操作为你:
public static Microsoft.AspNet.OData.Routing.ODataPath CreateODataPath(this Uri uri, HttpRequest request)
{
var pathHandler = request.GetPathHandler();
var serviceRoot = request.GetUrlHelper().CreateODataLink(
request.ODataFeature().RouteName,
pathHandler,
new List<ODataPathSegment>());
return pathHandler.Parse(serviceRoot, uri.LocalPath, request.GetRequestContainer());
}
如果您有这样的 Uri:
http://localhost:54321/OData/traits(1)
您可以将其拆分为 OData 段以获得例如导航:returnedPath.NavigationSource
或指定的键:returnedPath.Segments.OfType<KeySegment>().FirstOrDefault().Keys.FirstOrDefault().Value
关于asp.net-core - CreateRef 方法迁移到 .Net Core 导致 404,如何使用 .Net Core 在 OData 中实现创建关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49492428/