如何在MVC中使用WCF数据服务WebGet方法?

时间:2013-01-24 21:27:04

标签: wcf-data-services

假设我有一个WebGet方法:

[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);
}

我可以在浏览器中使用它:

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

但是,在MVC3控制器中我需要做什么才能调用该方法?我添加了服务引用,我可以使用上下文没有问题。下面的代码将状态列表吐出到/ 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);
}

我没有看到任何简单的方法来调用WebGet方法,但它没有像我期望的那样在服务上公开。我错过了什么吗?我可以通过这样做得到结果:

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);
}

..但这似乎有点荒谬。任何建议都非常感谢。

1 个答案:

答案 0 :(得分:0)

“添加服务引用”功能无法识别服务操作(即,在服务上使用[WebGet]声明的方法)。您可以使用ctx.Execute<T>()(与您一样)或ctx.CreateQuery<T>(),但我认为您不希望使用强类型解决方案。

有关详细信息,请参阅this page