我有代码来读取ASP.NET Web API的响应,如下所示:
HttpClient client = new HttpClient();
client.GetAsync(path.ToAbsoluteUrl()).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<DBResult>().ContinueWith(
(readTask) =>
{
result = readTask.Result;
lblMessage.Text = string.Format("{0} products were uploaded successfully. {1} failed.", result.Success, result.Failed);
});
});
Run Code Online (Sandbox Code Playgroud)
当我得到响应/结果时,我正在尝试显示某种消息.但似乎没什么用 - 我的标签没有更新.
显然,我做错了什么 - 如何在收到回复后向用户显示消息?
TIA
编辑:
如下所述,我宣布:
TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
并传入"调度程序"(尝试使用ContinueWiths),但仍然没有任何效果.实际上,现在我的lblMessage.Text上的断点未到达.
我想为Google搜索创建一个简单的异步请求.
根据谷歌的说法,最简单的方法是使用他们的JSON API和简单的curl请求
curl -e http://www.my-ajax-site.com \ 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton'
Run Code Online (Sandbox Code Playgroud)
我想拉出前5页的结果,并将每个结果的URL添加到数组中.我发现在HttpClient.GetAsync上找到任何解释良好的教程都难以置信.我没有比这更进一步:
public String[] search(String term = "")
{
var rq = new HttpClient();
var uri = new Uri("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:" + term);
rq.GetAsync(uri);
}
Run Code Online (Sandbox Code Playgroud)
我想这应该启动一个任务,所以我不会阻止主线程,但是如何在请求完成时注册一个回调方法?
简而言之,这是一个Windows应用商店应用程序,F5在Visual Studio 2013中运行时无法生成多个HTTP请求.目标平台是Windows 8.1.
每次单击按钮时,都会从公共服务器获取请求时间信息并显示响应.但是,正如Fiddler所示,尽管相关的点击事件处理程序一次又一次地运行,但实际的HTTP请求仅针对第一次点击.
我已经浏览了API文档和其他几个地方,但仍然没有.也许我忽略了某种配置问题,但我无法想象它会是什么.也许这里有人可以吗?
MainPage.xaml.cs中
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace TestWindowsStore
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private readonly Uri timeInfoHost = new Uri("http://jsontime-sharpnet.rhcloud.com/");
private readonly …Run Code Online (Sandbox Code Playgroud) 我正在寻找不会收到HTTP错误(例如404)的c#HTTP客户端。这不仅仅是样式问题;它对于非2xx回复具有主体是完全有效的,但是如果在执行GetResponse()时HTTP堆栈抛出异常,我将无法理解它
我有一个自定义的dto类:
public class myObject
{
public string Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和使用Web Api的控制器(4.5 .net框架)
[HttpPost]
public IHttpActionResult StripArchiveMailboxPermissions(myObject param)
{
DoSomething(param);
return OK();
}
Run Code Online (Sandbox Code Playgroud)
客户端只有4.0 .net框架所以我将无法使用PostAsJsonAsync()方法.将对象从我的客户端传递到服务器的解决方案是什么?
我试过像下面这样的东西:
var response = Client.SendAsync(new HttpRequestMessage<myObject>(objectTest)).Result;
Run Code Online (Sandbox Code Playgroud)
但它抛出了我的异常:
Could not load file or assembly 'Microsoft.Json, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
The system cannot find the file specified.
Run Code Online (Sandbox Code Playgroud)
是不是可以使用Newtonsoft.Json库?
对于我的一个项目,我想开发一个可以在不同平台(桌面,移动,表面等)中使用的库.因此选择了Porable Class Library.
我正在使用HttpClient开发一个用于调用不同API调用的类.我坚持如何调用方法,响应和解决方法.这是我的代码: -
public static async Task<JObject> ExecuteGet(string uri)
{
using (HttpClient client = new HttpClient())
{
// TODO - Send HTTP requests
HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Get, uri);
reqMsg.Headers.Add(apiIdTag, apiIdKey);
reqMsg.Headers.Add(apiSecretTag, ApiSecret);
reqMsg.Headers.Add("Content-Type", "text/json");
reqMsg.Headers.Add("Accept", "application/json");
//response = await client.SendAsync(reqMsg);
//return response;
//if (response.IsSuccessStatusCode)
//{
string content = await response.Content.ReadAsStringAsync();
return (JObject.Parse(content));
//}
}
}
// Perform AGENT LOGIN Process
public static bool agentStatus() {
bool loginSuccess = false;
try
{
API_Utility.ExecuteGet("http://api.mintchat.com/agent/autoonline").Wait();
// ACCESS Response, JObject ??? …Run Code Online (Sandbox Code Playgroud) 我不确定我是否没有得到大局,或者我是否只是错过了一些东西,但是将 JSON-String 解析为动态对象有什么好处?
如果我有一堂这样的课
class Product
{
public string Name { get; set; }
public double Price { get; set; }
public string Category { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我使用 HttpClient 来获取这样的对象
Product product = await response.Content.ReadAsAsync<Product>();
Run Code Online (Sandbox Code Playgroud)
我从这段代码中得到什么好处?
string content = await response.Content.ReadAsStringAsync();
dynamic product = JObject.Parse(content);
Run Code Online (Sandbox Code Playgroud)
如果我想使用它们,我需要写
product.Name
Run Code Online (Sandbox Code Playgroud)
使用强类型方法,我至少有智能感知。如果服务更改了产品,动态方法也无济于事,因为我仍然需要像上面提到的那样访问它。
那么我错过了什么?我为什么要使用动力学或何时使用?
我正在开发ASP.NET Core 2.0 RESTful API.我有一个场景,我需要使用HTTPGet方法在我的API控制器上调用操作,我需要提取用于调用另一个第三方API的用户名和密码值.用户名和密码与当前登录的用户标识无关,它们只是我想从我自己的API中发送到另一个API的值,但我不想只是在查询字符串中传递它们.
我可以在客户端中使用基本身份验证将用户名和密码添加到HttpRequestMessage身份验证标头中,然后在我的ASP.NET Core 2.0 API控制器操作中提取该标头吗?
我的客户端会在调用API的代码中出现类似的内容
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, relativeUrl);
var byteArray = new UTF8Encoding().GetBytes(string.Format($"username:password"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Run Code Online (Sandbox Code Playgroud)
而且,我的API控制器动作会启动这样的事情;
[HttpGet()]
public IActionResult GetUploadedFileList([FromQuery]int pageNumber, [FromQuery]int pageSize)
{
//Extract Authentication header values for username and password
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以提供如何从HTTPGet请求获取Authorization标头的示例
我意识到我可以使用HTTPPost [FromBody]轻松完成此操作,但我的用例要求此方法为HTTGet.
在此先感谢您的帮助.
编辑1 - 解决方案
由于此链接提供了一些提示,我能够让下面的代码工作.虽然这似乎很多工作,所以如果有人有更好或更清洁的解决方案,请发布你的例子.
[HttpGet()]
public IActionResult GetUploadedFiles([FromQuery]int pageNumber, [FromQuery]int pageSize)
{
string username = string.Empty;
string password = string.Empty;
if (Request.Headers.TryGetValue("Authorization", out StringValues authToken))
{
string authHeader = authToken.First(); …Run Code Online (Sandbox Code Playgroud) http-headers dotnet-httpclient asp.net-apicontroller asp.net-core-2.0
我正在设计一个.net核心Web API,它使用了我无法控制的外部API。我在堆栈溢出中找到了一些极好的答案,这些问题使我可以在使用semaphoreslim的同一线程中限制对此外部API的请求。我想知道如何最好地将这种限制扩展到整个应用程序,而不仅仅是限制特定任务列表。我一直在学习HttpMessageHandlers,这似乎是拦截所有传出消息并应用限制的一种可能方法。但是我担心线程安全性和锁定问题,我可能不了解。我包括了当前的限制代码,希望对理解我正在尝试做的事情有所帮助,但是要跨越多个线程,并且不断添加任务而不是预先定义的任务列表。
private static async Task<List<iMISPagedResultResponse>> GetAsyncThrottled(List<int> pages, int throttle, IiMISClient client, string url, int limit)
{
var rtn = new List<PagedResultResponse>();
var allTasks = new List<Task>();
var throttler = new SemaphoreSlim(initialCount: throttle);
foreach (var page in pages)
{
await throttler.WaitAsync();
allTasks.Add(
Task.Run(async () =>
{
try
{
var result = await GetPagedResult(client, url, page);
return result;
}
finally
{
throttler.Release();
}
}));
}
await Task.WhenAll(allTasks);
foreach (var task in allTasks)
{
var result = ((Task<PagedResultResponse>)task).Result;
rtn.Add(result);
}
return rtn; …Run Code Online (Sandbox Code Playgroud) 如本文所述,当我尝试对HttpClient使用类型化的客户端时收到错误消息:https ://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/http-requests?view = aspnetcore-2.2
这是我的设置:
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
services.AddHttpClient<IPStackService>(c =>
{
c.BaseAddress = new Uri(Configuration["IPStackURL"]);
});
services.AddHttpContextAccessor();
services.AddTransient<IIPStackService, IPStackService>();
}
Run Code Online (Sandbox Code Playgroud)
控制器:
[Route("api/[controller]")]
[ApiController]
public class RenderController : ControllerBase
{
private IConfiguration _configuration;
private readonly ILogger _logger;
private IIPStackService _ipMetaDataService;
public RenderController(IConfiguration configuration,
ILogger<RenderController> logger,
IIPStackService ipStackService)
{
_configuration = configuration;
_ipStackService = ipStackService;
_logger = logger;
}
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[Produces("text/plain")]
public async Task<ActionResult> GetAsync(string hostId, string clientUtc)
{
var ip = Common.ResolveIPAddress(HttpContext);
var ipMetaData …Run Code Online (Sandbox Code Playgroud) c# dependency-injection dotnet-httpclient asp.net-core asp.net-core-2.1
c# ×7
asp.net-core ×2
.net ×1
.net-4.5 ×1
async-await ×1
asynchronous ×1
dynamic ×1
http-headers ×1
json.net ×1
semaphore ×1
windows-8.1 ×1
wpf ×1