Search code examples
c#.netodata

Best way to pass throug URL query for oData Service .net c#


I have the following:

  1. WebAPI oData enabled Endpoint Applications with a small DB behind
  2. .NET MVC Front End with some HTML5 stuff and some program logic

I consume data through the service in (1) with the application in (2).

As application (1) is oData enabled, I want to give advanced users the option to write an URL filter in right in the browser when being in Application (2). So they could append something like this $top=2&$orderby=name

What would be the best way to grab that url filter and pass through to the oData Service in Application (2) ? I can't find a way to simple pass through a string. The only way I found around using a lync query, is AddQueryOptions.

Any suggestions ?

  // TODO: Replace with your local URI.
        string serviceUri = "http://localhost:14800/";
        var container = new Default.Container(new Uri(serviceUri));

        var product = new ODataDemoService.Models.Product();

        // grab 
        Uri myUri = new Uri("http://localhost:14800/Products?$top=2&$orderby=name");


        NameValueCollection nv = HttpUtility.ParseQueryString(myUri.Query);
        foreach (string key in nv)
        {
            // build a filter string here 
        }


        // Append the filter string using AddQueryOptions
        foreach (var p in container.Products.AddQueryOption("$filter","(Name eq 'Hat') or (Name eq 'Socks')"))
        {
            Console.WriteLine("{0} {1} {2}", p.Name, p.Price, p.Category);
        }   

Solution

  • You can use DataServiceContext.Execute<>

    var products = container.Execute<Product>(new Uri()), "GET"); // You can pass the Uri as what you want
    foreach(var p in products)
    {
        Console.WriteLine("{0} {1} {2}", p.Name, p.Price, p.Category);
    }