Search code examples
c#asp.net-web-api2odata

How to pass extra identifier to OData Controller


I'm having a OData controller named JobsController. This controller represents the Job entity

public class Job
{
  int Id {get;set;}
  int Name {get;set;}
...
}

In order to make a query I need the client to send me a contextId (database identifier). By checking the contextId the correct database is initialized. Obviously, contextId is not part of the Job model...

I wish my controller will look like that:

[HttpGet]
[ODataRoute("Jobs")]
[EnableQuery]
public IHttpActionResult Get()
{
    var unitOfWork = UnitOfWorkFactory.Create(contextId);

    if (unitOfWork == null)
        return InternalServerError(new Exception("Unit of work not found"));

    return Ok(unitOfWork.Jobs.GetAll());
}

I wish I could query something like this: http://localhost:38483/odata/Jobs('localDb') but it's not possible

or even http://localhost:38483/odata/Jobs/localDb


Solution

  • Firstly, this seems like a very odd way to be handling this, having one service that can connect to two different databases seems confusing, can you just setup two different endpoints instead?

    If you do require this to all be in one endpoint then OData has quite strict definitions for URLs based on the model/metadata that you setup and anything that you should be able to filter on etc should be included in the metadata so that a client can use the services by just consuming the metadata. If you want to include this within the URL then you will have to think about how that would apply to the metadata. Alternatively and preferably, you could use a custom header to achieve this.

    Using a custom header would just be a case of sending the header and retrieving this in your controller from the Request object

    To include this in your model, the best thing that I can think of is to setup contained entities so that you have http://localhost:38483/odata/localDb/Jobs/. You can find more information here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/odata-containment-in-web-api-22