您可以使用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