2013-07-07 165 views
2

我正在嘗試瞭解Web服務。美國政府有幾個可以使用的網絡服務,因此這可能是一個理想的開始。例如,這裏提供燃油經濟性信息http://www.fueleconomy.gov/feg/ws/index.shtmlWeb服務和ASP.NET MVC

如果我想在視圖(使用ASP.NET MVC)中顯示基本信息,例如當前的燃料價格(/ws/rest/fuelprices),我可以從哪裏開始?這似乎有很多方法可以做到這一點(WCF,SOAP?REST?也許我的方式離開基地??),我只需要一個基本的開始文檔,所以我可以溼透我的腳。

回答

4

您可以使用.NET 4.0中內置的新類HttpClient類來使用RESTful Web服務。例如,假設您想要返回當前的燃料價格(http://www.fueleconomy.gov/ws/rest/fuelprices)。

開始通過設計一個模型,映射XML,這個服務將返回:

[DataContract(Name = "fuelPrices", Namespace = "")] 
public class FuelPrices 
{ 
    [DataMember(Name = "cng")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal Cng { get; set; } 

    [DataMember(Name = "diesel")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal Diesel { get; set; } 

    [DataMember(Name = "e85")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal E85 { get; set; } 

    [DataMember(Name = "electric")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal Electric { get; set; } 

    [DataMember(Name = "lpg")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal Lpg { get; set; } 

    [DataMember(Name = "midgrade")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal MidGrade { get; set; } 

    [DataMember(Name = "premium")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal Premium { get; set; } 

    [DataMember(Name = "regular")] 
    [DisplayFormat(DataFormatString = "{0:c}")] 
    public decimal Regular { get; set; } 
} 

,那麼你可以有一個控制器,將查詢遠程REST服務,並將結果綁定到模型:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     using (var client = new HttpClient()) 
     { 
      var url = "http://www.fueleconomy.gov/ws/rest/fuelprices"; 
      var response = client.GetAsync(url).Result; 
      response.EnsureSuccessStatusCode(); 
      FuelPrices fuelPrices = response.Content.ReadAsAsync<FuelPrices>().Result; 
      return View(fuelPrices); 
     } 
    } 
} 

最後一個視圖來顯示結果:

@model FuelPrices 

<table> 
    <thead> 
     <tr> 
      <th>CNG</th> 
      <th>Diesel</th> 
      <th>E 85</th> 
      <th>Electric</th> 
      <th>LPG</th> 
      <th>Mid grade</th> 
      <th>Premium</th> 
      <th>Regular</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>@Html.DisplayFor(x => x.Cng)</td> 
      <td>@Html.DisplayFor(x => x.Diesel)</td> 
      <td>@Html.DisplayFor(x => x.E85)</td> 
      <td>@Html.DisplayFor(x => x.Electric)</td> 
      <td>@Html.DisplayFor(x => x.Lpg)</td> 
      <td>@Html.DisplayFor(x => x.MidGrade)</td> 
      <td>@Html.DisplayFor(x => x.Premium)</td> 
      <td>@Html.DisplayFor(x => x.Regular)</td> 
     </tr> 
    </tbody> 
</table> 
+0

感謝你爲這個。它確實幫助我理解Web服務如何與MVC協同工作。 – Robert