我试图在复数视频中关注该示例
当我尝试完成Api添加坐标时,我遇到了错误:
类型或命名空间名称' Http'名称空间中不存在System.Net' (你错过了一个程序集引用吗?)
这发生在以下课程中:
using Microsoft.Extensions.Logging;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net.Http;
namespace Moran.Services
{
public class CoordService
{
private ILogger<CoordService> _logger;
public CoordService(ILogger<CoordService> logger)
{
_logger = logger;
}
public async Task<CoordServiceResult> Lookup(string location)
{
var result = new CoordServiceResult()
{
Success = false,
Message = "Undetermined failures while looking up coordinates"
};
//Lookup Coordinates
var bingKey = Startup.Configuration["AppSettings:BingKey"];
var encodedName = WebUtility.UrlEncode(location);
var url = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={bingKey}";
var client = new HttpClient();
var json = await client.GetStringAsync(url);
// Read out the results
// Fragile, might need to change if the Bing API changes
var results = JObject.Parse(json);
var resources = results["resourceSets"][0]["resources"];
if (!resources.HasValues)
{
result.Message = $"Could not find '{location}' as a location";
}
else
{
var confidence = (string)resources[0]["confidence"];
if (confidence != "High")
{
result.Message = $"Could not find a confident match for '{location}' as a location";
}
else
{
var coords = resources[0]["geocodePoints"][0]["coordinates"];
result.Latitude = (double)coords[0];
result.Longitude = (double)coords[1];
result.Success = true;
result.Message = "Success";
}
}
return result;
}
}
}
当我尝试添加
时会发生这种情况var client = new HttpClient();
任何想法为什么会这样?
我找不到任何理由不编译......
答案 0 :(得分:5)
HttpClient
类位于System.Net.Http
命名空间中,位于System.Net.Http.dll
。要在ASP.NET 5项目中使用此类,您需要将System.Net.Http
添加到"dependencies"
文件中的json数据的project.json
部分
"dependencies": {
"Microsoft.AspNet.Diagnostics": "1.0.0-beta5",
"Microsoft.AspNet.Mvc": "6.0.0-beta5",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5",
"Microsoft.AspNet.Server.IIS": "1.0.0-beta5",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta5",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta5",
"Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta5",
"Microsoft.Framework.Logging": "1.0.0-beta5",
"Microsoft.Framework.Logging.Console": "1.0.0-beta5",
"System.Net.Http": "4.0.1-beta-23409"
},
4.0.1-beta-23409
是撰写本文时的最新版本。 Visual Studio intellisense将为您提供多个可用版本,您可以选择最新/稳定版本。
进行此更改后,当您保存文件时,它将执行 dnu恢复(通常会根据需要下载必要的软件包)并添加对 System.Net.Http 程序集。您可以在类中添加using语句并开始使用HttpClient
类。
using System;
using System.Net.Http;
public class SomeClass
{
public void SomeMethod()
{
var client = new HttpClient();
}
}