我使用Nuget安装"Microsoft ASP.NET Web API客户端库"以获取最新的System.Net.Http程序集,以便在Windows Phone 7.1 XNA和Silverlight项目中使用.它在我的WP7.1 XNA项目中安装得很好,但是不允许我将它安装到WP7.1 Silverlight项目中.我甚至尝试将它从Package Manager Console直接安装到新创建的WP7.1 Silverlight项目中,并获得此错误响应:
PM> Install-Package System.Net.Http
Attempting to resolve dependency 'Microsoft.Net.Http (? 2.0.20710.0 && < 2.1)'.
You are downloading Microsoft.Net.Http from Microsoft, the license agreement to which is available at http://www.microsoft.com/web/webpi/eula/MVC_4_eula_ENU.htm. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant …Run Code Online (Sandbox Code Playgroud) 我正在使用一个httpclient实例发送多个请求来休息web api以获取数据.这是我的代码的样子:
首先,我有一个控制层,用于调用数据的数据层.
public class ControlLayer
{
protected DataLayer dal;
//constructors here
public int getInfo1(int param)
{
int ret = this.dal.getInfo1(param);
return ret;
}
public int getInfo2(int param)
{
int ret = this.dal.getInfo2(param);
return ret;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有调用webAPI的dataLayer,它看起来像这样.这里为了简单起见,我直接使用.result.
public class DataLayer
{
HttpClient client = new HttpClient();
string url = "";
public int getInfo1(int param1)
{
int ret=0;
HttpResponseMessage response = client.GetAsync(url).Result;
//.... do some work, get the value for ret
return ret;
}
public int getInfo2(int param1)
{
int …Run Code Online (Sandbox Code Playgroud) 使用VS 2010,VB.NET,HTTPClient,.NET 4.0和Windows窗体.
我试图让Windows应用程序使用来自我创建的Web API的JSON.Web API运行良好,我可以从浏览器查看结果.发现这篇文章我一直试图只使用VB.NET而不是C#. http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application
代码的关键部分是这个函数:
private void GetProducts(object sender, RoutedEventArgs e)
{
btnGetProducts.IsEnabled = false;
client.GetAsync("api/products/2").ContinueWith((t) =>
{
if (t.IsFaulted)
{
MessageBox.Show(t.Exception.Message);
btnGetProducts.IsEnabled = true;
}
else
{
var response = t.Result;
if (response.IsSuccessStatusCode)
{
response.Content.ReadAsAsync<IEnumerable<Product>>().
ContinueWith(t2 =>
{
if (t2.IsFaulted)
{
MessageBox.Show(t2.Exception.Message);
btnGetProducts.IsEnabled = true;
}
else
{
var products = t2.Result;
_products.CopyFrom(products);
btnGetProducts.IsEnabled = true;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)
我试图将其转换为VB.NET,但我遇到了t.Result的问题,"'结果'不是'System.Threading.Tasks.Task'的成员."
这是我尝试将其转换为VB.NET:
Private Sub GetProducts(sender As Object, e As RoutedEventArgs)
btnGetProducts.IsEnabled = …Run Code Online (Sandbox Code Playgroud) 我有一个从Web服务获取大量JSON的函数.这个数据有时可能很大,千兆字节.我的电话看起来像这样.
try
{
using (var httpClient = NewHttpClient())
{
var response = httpClient.GetAsync(endpoint).Result;
return response;
}
}
catch(Exception ex)
{
//Do Stuff
}
Run Code Online (Sandbox Code Playgroud)
当数据很大时,会抛出内存不足异常.我相信这是因为响应消息实际上比HttpResponseMessage允许它更大.有没有办法在一段时间内只得到一些消息?我确信它以前已经完成,但我无法找到谷歌和/或斜杠的任何东西.提前感谢您的建议.
我会尽量简化我的情况,使其更加简洁明了.所以,我正在开发一个WinRT应用程序,用户在2秒钟后输入文本,TextBox并在其TextChanged事件中,我需要根据用户文本发出远程请求来获取数据.
现在,用户输入文本并初始化了Web请求,但用户立即写入另一个术语.所以,我需要取消第一个Web请求并启动新的请求.
请将以下内容视为我的代码:
private CancellationTokenSource cts;
public HomePageViewModel()
{
cts = new CancellationTokenSource();
}
private async void SearchPeopleTextChangedHandler(SearchPeopleTextChangedEventArgs e)
{
//Cancel previous request before making new one
//GetMembers() is using simple HttpClient to PostAsync() and get response
var members = await _myService.GetMembers(someId, cts.Token);
//other stuff based on members
}
Run Code Online (Sandbox Code Playgroud)
我知道CancellationToken在这里发挥作用,但我无法弄清楚如何.
c# task task-parallel-library windows-runtime dotnet-httpclient
我有一个方法ReadJsonUrl获取一个url(字符串地址(例如:https ://www.ah.nl/service/rest/delegate?url=%2Fproducten%2Fproduct%2Fwi224732%2Fsmiths-nibb-it-happy- ones-kruis-rond-paprika))到JSON文件.
此方法读取JSON并在控制台中输出一些数据.
但问题是产品的描述输出如
Smiths Nibb-it hap-py on-es kruis-rond pa-pri-ka
但如果我在我的浏览器中检查JSON它会显示
史密斯Nibb-它快乐的kruis-rond辣椒粉
这就是我想要它打印的方式.
我认为问题是,请求是使用0px x 0xx分辨率浏览器完成的,因此它会返回分开的单词以使其可读.如果我使我的浏览器非常小,那么它也会用破折号显示描述.我在我的代码中添加了一个用户代理,但是没有用.
有谁知道如何解决这个问题?
我的代码:
public static async Task<object> ReadJsonUrl(string address)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
HttpResponseMessage response = await client.GetAsync(address);
var content = await response.Content.ReadAsStringAsync();
//JObject obj = JObject.Parse(content);
var data = Empty.FromJson(content);
var product = data.Embedded.Lanes[4].Embedded.Items[0].Embedded.Product;
Console.WriteLine(product.Id);
Console.WriteLine(product.Description);
Console.WriteLine(product.PriceLabel.Now);
Console.WriteLine(product.Availability.Label);
Console.WriteLine("-------------------------------------");
System.Threading.Thread.Sleep(5000);
//the return value is …Run Code Online (Sandbox Code Playgroud) 当我尝试GET使用下面的地址和授权值进行请求时,我没有任何问题。
地址:http://example.com/xyz.svc/branches/?latitude = 0&longitude = 0&range = 20000
标头密钥:授权
值:example; foo
当我尝试使用时,HttpCLient出现授权标头值的格式无效错误
这就是我尝试的方式
HttpClient client = new HttpClient();
string latitude = "0";
string longitude = "0";
string range = "2000";
string uri = "/xyz.svc/branches/?latitude=0&longitude=0&range=20000;
string value = "foo";
client.BaseAddress = new Uri("http://example.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Authorization", String.Format("example;{0}", value));
HttpResponseMessage response = await client.GetAsync(uri);
var responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我正在使用支持JSON格式的POST请求的RESTful API。API自己的Swagger文档显示这是对其端点之一的有效调用:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '<JSON>' '<URL>'
Run Code Online (Sandbox Code Playgroud)
其中<JSON>和<URL>是有效的JSON消息和端点的URL。从Swagger文档中,我收集到该端点的所有帖子都必须同时包含Content-Type和Accept设置为的标头application/json。
我正在编写一个C#方法,该方法将使用.NET Core的HttpClient类发布到此终结点。但是,发布消息后,我收到HTTP 415错误代码,表示不支持的媒体类型。根据到目前为止的了解,Content-Type必须在您的内容中设置标题(我正在使用StringContent该类),并且Accept只能在HttpClient标题中设置标题。这是我的特定示例:
var httpContent = new StringContent("<JSON>", Encoding.UTF32, "application/json");
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = httpClient.PostAsync("<URL>", httpContent);
var result = responseMessage.Result;
Run Code Online (Sandbox Code Playgroud)
再一次,在<JSON>和<URL>是有效JSON消息以及端点的URL。在我看来,我引用的第三行httpCllient.DefaultRequestHeaders没有在Accept: application/json请求中添加标题。如果我手动将标头添加到httpContent.Headers集合中,Accept则会收到运行时错误消息,告诉我不是我可以添加到标头中的标头httpContent。这就是为什么我希望将其添加到httpClient。
我已经使用Swagger验证了URL和JSON,所以我知道它们是正确的。另外,请求是通过HTTPS完成的,所以我无法使用Fiddler来验证 …
我创建了Web API以从OpenWeatherAPI接收每日温度.
现在我想在我的MVC网页上显示所有内容.我把API调用放在了MVC项目中; 计划稍后创建新项目以获得更好的微服务架构.
我在Debug窗口和MVC html中看到这些错误,如下所示.如何在html上显示天气,温度等,降水量.
Debug: weathercontroller.City("Seattle") The function evaluation requires all threads to run. System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>"
HTML: System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[Microsoft.AspNetCore.Mvc.IActionResult,WeatherChecker.Controllers.WeatherController+<City>d__0]"
Run Code Online (Sandbox Code Playgroud)
MVC页面:
namespace WeatherPage.Controllers
{
public class HomeController : Controller
{
public WeatherController weathercontroller = new WeatherController();
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
ViewData["test"] = weathercontroller.City("Seattle");
return View();
}
Run Code Online (Sandbox Code Playgroud)
API控制器:
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
[HttpGet("[action]/{city}")]
public async Task<IActionResult> City(string city)
{
Rootobject rawWeather = new Rootobject();
using (var …Run Code Online (Sandbox Code Playgroud) c# dotnet-httpclient asp.net-core-mvc asp.net-core asp.net-core-webapi
我有一个简单的Asp.Net CoreWebApi,HttpClient用于发送一些custum Web请求。我这样使用HttpClient:
services.AddHttpClient<IMyInterface, MyService>()
...
public class MyService : IMyInterface
{
private readonly HttpClient _client;
public MyService(HttpClient client)
{
_client = client;
}
public async Task SendWebRequest()
{
var url = "https://MyCustomUrl.com/myCustomResource";
var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = await _client.SendAsync(request);
...
}
}
Run Code Online (Sandbox Code Playgroud)
我注意到,当我发送多个请求时,HttpClient将它收到的带有第一次响应的 cookie保存在Set-Cookie标头中。它将那些cookie添加到连续的请求标头中。(我已经用进行了检查fiddler)。流:
//First requst
GET https://MyCustomUrl.com/myCustomResource HTTP/1.1
//First response
HTTP/1.1 200 OK
Set-Cookie: key=value
...
//Second request
GET …Run Code Online (Sandbox Code Playgroud) c# ×9
asp.net-core ×2
json ×2
.net-core ×1
async-await ×1
cookies ×1
http-error ×1
http-headers ×1
silverlight ×1
system.net ×1
task ×1
vb.net ×1
vb.net-to-c# ×1