Saturday, May 27, 2023

OData Route 404 Error after Migrating from .NET Framework to .NET Core

 I have a global OData function in .NET Framework that uses a routing attribute:

[ODataRoute("GetSalesStats(SellerId={sellerId}, BuyerId={buyerId}, FromTime={fromTime}, ToTime={toTime})")]

This was working fine. Now with .NET 7 (.NET Core), I started using HttpGet attribute for routing:

[HttpGet("odata/GetSalesStats(SellerId={sellerId}, BuyerId={buyerId}, FromTime={fromTime}, ToTime={toTime})")]

This did not work. The difference is that the HttpGet attribute does not like the spaces after the commas. After removing the spaces, the following works fine:

[HttpGet("odata/GetSalesStats(SellerId={sellerId},BuyerId={buyerId},FromTime={fromTime}, ToTime={toTime})")]

Now I just need to go find all the spaces that I need to remove:-).

Update: When an entity has multiple key columns, the "OData Connected Service" tool for adding "Connected Service" in Visual Studio 2022 seems to add the key columns in alphabetical order. When you have routing attribute specified for an OData action, and the order of the parameters is different, you will get an HTTP 404 error as well. For example, for querying by primary key, you would have something like

[HttpGet("odata/UserData(PropertyName={propertyName},UserId={userId})")]

Even though you would setup the UserId as the first key column and the PropertyName as the second key column, the generated OData client always sends in the PropertyName as the first parameter, and the UserId as the second parameter. If you specify them in the "wrong" order, you will get an HTTP 404 error for it.