TL; DR:我是这种语言的新手,不知道我在做什么
到目前为止,这是我的班级:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web;
using System.Net;
using System.IO;
public class MyClass
{
private const string URL = "https://sub.domain.com/objects.json?api_key=123";
private const string data = @"{""object"":{""name"":""Title""}}";
public static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
try
{
// get the response
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
}
catch (WebException we)
{
string webExceptionMessage = we.Message;
}
catch (Exception ex)
{
// no need to do anything special here....
}
}
static void Main(string[] args)
{
MyClass.CreateObject();
}
}
Run Code Online (Sandbox Code Playgroud)
当我做csc filename.cs时,我收到以下错误:
名称空间'System.Net'中不存在类型或命名空间名称'Http'(您是否缺少程序集引用?)
M.B*_*ock 103
HttpClient住在System.Net.Http命名空间中.
你需要添加:
using System.Net.Http;
Run Code Online (Sandbox Code Playgroud)
并确保您System.Net.Http.dll在.NET 4.5 中引用.
发布的代码似乎没有做任何事情webClient.实际编译的代码是否有问题HttpWebRequest?
更新
要打开添加引用.在项目对话框右键单击解决方案资源管理器,然后选择添加引用....它应该看起来像:

use*_*812 76
NuGet> Microsoft ASP.NET Web API客户端库
小智 14
我是怎么解决的
在我的情况下,我在开始.Net 4.0和"Assemblies" - >"Extensions"选项"System.Net.Http"与版本2.0.0.0.在我的操作"Assemblies" - >"Framework"选项"System.Net.Http"和"System.Net.Http"之后有相同的4.0.0.0版本.
假设你使用Visual Studio 10,你可以在这里为Visual Studio 10 下载包含System.Net.Http的安装: 下载VSC的MVC4
安装完成后,右键单击VS Project中的References文件夹,然后选择Add Reference.然后,选择" 浏览"选项卡.导航到MVC4安装的程序集安装路径(通常在Program Files(x86)/ Microsoft ASP.NET/ASP.NET MVC4/assemblies中),然后选择名为"System.Net.Http.dll"的程序集.现在,您可以在代码顶部添加"using System.Net.Http"并开始创建HttpClient连接.