您可以使用WCF消费服务。像这样:
[ServiceContract]
public interface IDogService
{
[OperationContract]
[WebGet(UriTemplate = "/api/dog")]
IEnumerable<Dog> List();
}
public class DogServiceClient : ClientBase<IDogService>, IDogService
{
public DogServiceClient(string endpointConfigurationName) : base(endpointConfigurationName)
{
}
public IEnumerable<Dog> List()
{
return Channel.List();
}
}
然后你就可以在你的控制器使用它:
public class HomeController : Controller
{
public HomeController()
{
}
public ActionResult List()
{
var service = new DogServiceClient("YourEndpoint");
var dogs = service.List();
return View(dogs);
}
}
而且在你的web.config您将配置您的端点:
<system.serviceModel>
<client>
<endpoint address="http://localhost/DogService" binding="webHttpBinding"
bindingConfiguration="" behaviorConfiguration="DogServiceConfig"
contract="IDogService" name="YourEndpoint" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="DogServiceConfig">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
+1我在我的网络应用程序中就像这样做 –
这看起来不错,但我无法得到异步/等待的东西工作。 IDE不喜欢这些关键字。我正在使用.NET 4.0,并使用NuGet安装了Web API客户端库。 –
@GlennArndt除非你采取一些更多的行动,否则你不能在.NET 4.0中使用async/await。看到这篇博文:http://blogs.msdn.com/b/bclteam/archive/2012/10/22/using-async-await-without-net-framework-4-5.aspx您可以利用异步控制器操作没有异步和等待关键字,但它会变得混乱。 – tugberk