You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 3.1端点路由下OData V7备用键配置问题

Hey there! I see you're trying to get OData alternate keys working with ASP.NET Core 3.1 and endpoint routing, and you're stuck on configuring the AlternateKeysODataUriResolver. You're right that this resolver is critical—here's exactly how to set it up properly in endpoint routing mode:

Fixing Alternate Key Configuration for OData V7 + ASP.NET Core 3.1

1. Register the Alternate Key Resolver in ConfigureServices

In endpoint routing mode, resolver configuration happens when you add OData services, not in the UseEndpoints block. Update your ConfigureServices method to explicitly set the resolver:

using Microsoft.OData.UriParser;

public void ConfigureServices(IServiceCollection services)
{
    // Keep your existing service registrations (DbContext, Razor Pages, Blazor, etc.)
    services.AddDbContext<YourDbContext>(options => /* your config */);
    services.AddRazorPages();
    services.AddServerSideBlazor();

    // Configure OData with the alternate key resolver
    services.AddControllers()
        .AddOData(options =>
        {
            // Enable standard OData query features
            options.Select().Filter().OrderBy().Count().MaxTop(20);
            
            // Register the resolver that handles alternate keys
            options.SetODataOptions(o => o.UriResolver = new AlternateKeysODataUriResolver());
            
            // Add your EDM model and route prefix
            options.AddRouteComponents("api", GetEdmModel());
        });
}

2. Simplify Your Configure Method

Since you're now configuring OData routes in ConfigureServices, you can remove the MapODataRoute line from your UseEndpoints block to avoid conflicts:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Keep your existing middleware (error handling, static files, routing, etc.)
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
        // Remove the old endpoints.MapODataRoute(...) line here
    });
}

3. Verify Your EDM Model & Controller

Your existing EDM model setup for alternate keys is correct—casting to EdmModel to add the alternate key annotation is the right approach for OData V7.

For your controller, the custom route [ODataRoute("Employees(UserId={userid})")] will now work as expected because the resolver recognizes the alternate key syntax. You can also simplify it to use OData's automatic key resolution if you prefer:

[EnableQuery]
[ODataRoute("Employees({userid})")] // OData will resolve this to the alternate key
public async Task<IActionResult> GetByUserId([FromODataUri] string userid)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    var record = await Context.Employees.FirstOrDefaultAsync(r => r.UserId == userid);
    return record == null ? NotFound() : Ok(record);
}

The AlternateKeysODataUriResolver tells OData's URI parser to recognize and process alternate key segments in requests, which is what was missing in your original setup.

内容的提问来源于stack exchange,提问作者Scott

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:23:01