标签: dotnet-httpclient

等待System.Threading.Task并忽略结果?

我试图通过直接潜入并尝试将一些C#代码转换为它来学习F#.我正在重写的一件事是异步方法的一部分,它等待调用HttpClient的GetAsync而不使用结果.那是:

await httpClient.GetAsync("http://www.example.com");
Run Code Online (Sandbox Code Playgroud)

以下是我尝试过的唯一没有得到红色波浪形的东西.虽然我认为它是有效的,但它确实创建了一个我可能想要避免的变量.

let! ignoreme = Async.AwaitTask <| httpClient.GetAsync("http://www.example.com")
Run Code Online (Sandbox Code Playgroud)

该怎么做?

f# async-await dotnet-httpclient

3
推荐指数
1
解决办法
901
查看次数

设置逗号时,System.Net.Http.HttpClient实例会引发异常.为什么?

鉴于以下System.Net.Http.HttpClient Portable Class Library引发异常:

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", "aaaa,bbbb");
Run Code Online (Sandbox Code Playgroud)

例外情况是:格式无效

1 values, System.Net.Http.Headers.HeaderInfo headerInfo, Boolean ignoreInvalid) [0x0004c] in /Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http.Headers/HttpHeaders.cs:195 at System.Net.Http.Headers.HttpHeaders.Add (System.String name, IEnumerable/Developer/MonoTouch/Source/mono/mcs/class/System.Net.Http/System.Net.Http 中的System.Net.Http.Headers.HttpHeaders.AddInternal(System.String name,IEnumerable 1 values)[0x00011] .Headers/HttpHeaders.cs:170位于/ Developer/MonoTouch/Source/mono/mcs/class/System中的System.Net.Http.Headers.HttpHeaders.Add(System.String name,System.String value)[0x00000]. Net.Http/System.Net.Http.Headers/HttpHeaders <... snip ...>

现在这只发生在以下情况

标题键= Authorization.如果你把它改成其他任何东西,那没关系.值=必须有逗号.

现在,这个先前的SO问题表明逗号是在标题中粘贴多个值的正确方法.

谁能解释一下发生了什么?

注意:这是在Xamarin上,所以我猜它是单声道的.不确定这是否重要.

更新:

这是一张照片.

在此输入图像描述

.net c# http-headers dotnet-httpclient

3
推荐指数
1
解决办法
3496
查看次数

在任务延续期间阻止异步HttpClient调用时死锁

我试图绕过同步调用异步函数和死锁.

在下面的例子中,我阻止了一个内部使用ConfigureAwait(false)的异步调用,据我所知,这应该可以防止死锁.第一次调用Web服务不会死锁.但是,第二个发生在同步回到UI线程死锁的延续中.

GetBlocking_Click是WPF应用程序中的单击事件,因此第一个和第二个请求都发生在UI线程上.

      private void GetBlocking_Click(object sender, RoutedEventArgs e)
    {
        const string uri = "http://www.mywebservice.com";
        var example1 = GetAsync(uri).Result;

        Task.FromResult(true)
            .ContinueWith(t =>
            {
                var example2 = GetAsync(uri).Result;
            }, 
            TaskScheduler.FromCurrentSynchronizationContext()).Wait();
    }

    private async Task<string> GetAsync(string url)
    {
        using (var client = new HttpClient())
        {
            var responseMessage = await client.GetAsync(url).ConfigureAwait(false);

            return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
        }
    }
Run Code Online (Sandbox Code Playgroud)

你能解释一下这两个电话有什么区别吗?

c# deadlock task async-await dotnet-httpclient

3
推荐指数
1
解决办法
1742
查看次数

Xamarin表示PCL - 网络请求的简洁方法?

我正在构建一个带有便携式类库的Android/iOS xamarin表单应用程序.我正在寻找在PCL项目中执行此示例的最佳方法:

https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create (
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
           Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open …
Run Code Online (Sandbox Code Playgroud)

httpwebrequest portable-class-library dotnet-httpclient xamarin xamarin.forms

3
推荐指数
1
解决办法
7774
查看次数

将字典键从json反序列化到.net中的枚举

我正在从API中读取json响应,其中包含有关图像的信息.
它是这样的字典格式:

images: {
    low_resolution: {
        url: "...",
        width: 150,
        height: 150
    },
    high_resolution: {
        url: "...",
        width: 450,
        height: 450
    }
}
Run Code Online (Sandbox Code Playgroud)

我将响应反序列化为对象,并将图像转换为Dictionary属性,如下所示:

[DataContract()]
public class Post
{
    ...
    [DataMember(Name = "images")]
    public IDictionary<string, Media> Images { get; set; }
    ...
}

HttpResponseMessage response = await client.GetAsync(query);
if (response.IsSuccessStatusCode)
{
    post = await response.Content.ReadAsAsync<Post>();
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这一切都很好,但我宁愿将图像分辨率信息反序列化为枚举值.
所以我创建了一个枚举ImageResolution并将字典键更改stringImageResolution.

这也成功反序列化,只要实际的枚举值等于json字符串,但我想更改枚举值.
根据其他各种帖子,我尝试了以下内容:

[DataContract()]
public enum ImageResolution
{
    [EnumMember(Value = "low_resolution")]
    Low,

    [EnumMember(Value = "high_resolution")] …
Run Code Online (Sandbox Code Playgroud)

.net c# json.net deserialization dotnet-httpclient

3
推荐指数
1
解决办法
2420
查看次数

如何在Xamarin Android(API 16 - 19)上启用TLSv1.1 +?

我正在尝试启用TLSv1.1TLSv1.2为我的Android应用程序(使用Xamarin构建).Android API 16+支持1.1和1.2,但默认情况下不启用API 20().任何人都可以解释如何启用TLSv1.1TLSv1.2使用.Net的HttpClient(或推荐替代HttpClient).

ssl android dotnet-httpclient xamarin

3
推荐指数
1
解决办法
848
查看次数

使用HttpClient时,如何在Content-Type中不排除charset?

我试图在.net核心项目中使用HttpClient向接受/返回JSON的REST服务发出GET请求.我不控制外部服务.

不管我如何努力,我想不出来设置Content-Type头的应用程序/ JSON .

我用的时候

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Run Code Online (Sandbox Code Playgroud)

它发送HTTP GET请求:

Content-Type: application/json; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

但是,此特定服务不适用于此.它仅在标题为:

Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)

我已经尝试设置标头而不进行验证,我在网络/ SO上找到的所有方法都不适用于.net核心.所有其他发送HTTP请求的方法在.net核心中都不可用,所以我需要弄明白这一点.如何在内容类型中排除字符集?

编辑与解决方法

如答案中所述,该服务应使用Accept标头.解决方法(正如Shaun Luttin在他的回答中所说)是在GET中添加一个空内容(什么?GET没有内容!是的......).它不漂亮,但确实有效.

.net c# dotnet-httpclient asp.net-core

3
推荐指数
1
解决办法
2421
查看次数

为什么我的属性路由不起作用?

这是我的控制器的外观:

[Route("api/[controller]")]
[Produces("application/json")]
public class ClientsController : Controller
{
    private readonly IDataService _clients;

    public ClientsController(IDataService dataService)
    {
        _clients = dataService;
    }

    [HttpPost]
    public int Post([Bind("GivenName,FamilyName,GenderId,DateOfBirth,Id")] Client model)
    {
        // NB Implement.
        return 0;
    }

    [HttpGet("api/Client/Get")]
    [Produces(typeof(IEnumerable<Client>))]
    public async Task<IActionResult> Get()
    {
        var clients = await _clients.ReadAsync();
        return Ok(clients);
    }

    [HttpGet("api/Client/Get/{id:int}")]
    [Produces(typeof(Client))]
    public async Task<IActionResult> Get(int id)
    {
        var client = await _clients.ReadAsync(id);
        if (client == null)
        {
            return NotFound();
        }

        return Ok(client);
    }

    [HttpGet("api/Client/Put")]
    public void Put(int id, [FromBody]string value) …
Run Code Online (Sandbox Code Playgroud)

asp.net-mvc attributerouting dotnet-httpclient asp.net-core-mvc

3
推荐指数
2
解决办法
2751
查看次数

HttpClient PostAsync和SendAsync之间的区别

在一个WPF前端的项目上工作,并试图处理异步调用HttpClient,我一直在试图让PostAsync工作,但它通常似乎陷入僵局,或者至少是后期响应超时,即使有超时的大值,也有提琴手的可见响应.

所以,过了一段时间我决定尝试在HttpClient上使用其他几种方法,然后他们就开始尝试了.不知道为什么.

我是干净的一路我的WPF按钮,awaits,asyncs,和.ConfigureAwait(false)(我认为):

按钮:

private async void Generate_Suite_BTN_Click(object sender, RoutedEventArgs e)
{
    await suiteBuilder.SendStarWs().ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

XmlDoc加载:

internal async Task SendStarWs()
{
    var xmlDoc = new XmlDocument();
    xmlDoc.Load("C:\\Temp\\file.xml");
    await StarWSClient.SendStarMessage(xmlDoc).ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

发信息:

private static readonly HttpClient Client = new HttpClient {MaxResponseContentBufferSize = 1000000};

public static async Task<STARResult> SendMessage(vars)
{
var response = await SendRequestAsync(url, contentNew, Client).ConfigureAwait(false);
return new STARResult(response, hash);
}
Run Code Online (Sandbox Code Playgroud)

我立即打电话给我的终点'500s',我期待:

var response = await SendRequestAsync(url, contentNew, Client).ConfigureAwait(false);

private static async Task<HttpResponseMessage> SendRequestAsync(string adaptiveUri, …
Run Code Online (Sandbox Code Playgroud)

c# wpf async-await dotnet-httpclient

3
推荐指数
1
解决办法
9906
查看次数

请求发现底座时出错(需要HTTPS)

我正在使用身份服务器4。事实上,它仍然可以正常工作,一切正常。但是当我尝试打电话时

var client = new HttpClient();
// discover endpoints from metadata
var disco = client.GetDiscoveryDocumentAsync(IDPBaseURL).Result;
it gives me error         
http://xxx.x.x.xx:8080/.well-known/openid-configuration: HTTPS required.
Run Code Online (Sandbox Code Playgroud)

它可以在Visual Studio和本地IIS部署中使用。但是我仅在服务器上部署时才遇到此错误。

任何的想法?

c# dotnet-httpclient asp.net-core identityserver4

3
推荐指数
2
解决办法
675
查看次数