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

How to change route in WebApi+Odata project


I'm re-implementing WCF service and I choose to use WebAPI 2.2 + OData v4. Problem I'm facing is that I need to have route which contains '_' and I'm unable to implement it. Currently I have this:

public class AnnotationSharedWithController : ODataController
{
    ...
    [EnableQuery]
    public IQueryable<AnnotationSharedWith> Get()
    {
        return _unitOfWork.AnnotationSharedWith.Get();
    }
    ...
}

and my WebApiConfig.cs looks like this:

public static void Register(HttpConfiguration config)
{
    config.MapODataServiceRoute("webservice",null,GenerateEdmModel());
        config.Count();
}

private static IEdmModel GenerateEdmModel()
{
    var builder = new ODataConventionModelBuilder();
    builder.EntitySet<AnnotationSharedWith>("annotation_shared_with");
        return builder.GetEdmModel();
}

When I issue GET request I receive following error

{ "Message": "No HTTP resource was found that matches the request URI 'http://localhost:12854/annotation_shared_with'.", "MessageDetail": "No type was found that matches the controller named 'annotation_shared_with'." }


Solution

  • Your could use routing attributes to achieve this:

    1. Using ODataRouteAttribute class:

      public class AnnotationSharedWithController : ODataController
      {
          [EnableQuery]
          [ODataRouteAttribute("annotation_shared_with")]
          public IQueryable<AnnotationSharedWith> Get()
          {
              //your code
          }
      }
      
    2. Using ODataRoutePrefixAttribute and ODataRouteAttribute classes:

      [ODataRoutePrefixAttribute("annotation_shared_with")]
      public class AnnotationSharedWithController : ODataController
      {
          [EnableQuery]
          [ODataRouteAttribute("")]
          public IQueryable<AnnotationSharedWith> Get()
          {
              //your code
          }
      }