2

我正在尝试了解网络服务。美国政府有几个可以使用的 Web 服务,因此这可能是一个理想的起点。例如,这是一个提供燃油经济性信息的 网站 http://www.fueleconomy.gov/feg/ws/index.shtml

如果我想在视图中显示基本信息(使用 ASP.NET MVC),例如当前燃料价格(/ws/rest/fuelprices),我该如何/从哪里开始?似乎有很多方法可以做到这一点(WCF?SOAP?REST?也许我离基地很远??)我只需要一个基本的入门文档,这样我就可以开始了。

4

1 回答 1

4

HttpClient您可以使用.NET 4.0 中内置的新类来使用 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>
于 2013-07-07T17:07:25.730 回答