Search code examples
wcf-data-services

How to consume WCF Data Service WebGet method in MVC?


Lets say I have a WebGet method:

[WebGet]
public IQueryable<State> GetStatesStartingWithLetter(string letter)
{
     return CurrentDataSource.States.Where(s => s.Name.Substring(0, 1).Equals(letter.Substring(0, 1),
            StringComparison.InvariantCultureIgnoreCase)).OrderBy(s => s.Name);
}

I can consume it in a browser like so:

http://localhost:55576/WcfDataService.svc/GetStatesStartingWithLetter?letter='a'

However, what do I have to do in an MVC3 controller to call the method? I have added the service reference and I can use the context without a problem. The code below spits a list of states out to the screen at the /Controller/States URL.

public ActionResult States()
{
    MyDbContext ctx = new MyDbContext(new Uri("http://localhost:55576/WcfDataService.svc/"));

    var temp = from state in ctx.States
               select state;

    return View(temp);
}

I don't see any EASY way to just call the WebGet method though, its not exposed on the service as I would expect it to be. Am I missing something? I can get the results by doing this:

public ActionResult States()
{
    WhelenDbContext ctx = new WhelenDbContext(new Uri("http://localhost:55576/WcfDataService.svc/"));

    var temp = ctx.Execute<State>(new Uri("http://localhost:55576/WcfDataService.svc/GetStatesStartingWithLetter?letter='a'"));

    return View(temp);
}

..but that seems a bit ridiculous. Any suggestions are much appreciated.


Solution

  • The "add service reference" functionality doesn't recognize service operations (i.e., methods declared with [WebGet] on the service). You can use either ctx.Execute<T>() (like you have) or ctx.CreateQuery<T>(), but neither are the strongly-typed solution I think you were hoping for.

    For more information, see this page.