有谁知道如何向WebView控件提供凭据(甚至更好-在特定域用户的上下文中运行Windows 8 Metro风格的应用程序/ WinRT应用程序?)我尝试按照此处列出的HttpClient + WebView方法进行操作( http://social.msdn.microsoft.com/Forums/zh-CN/winappswithcsharp/thread/05e46a0a-e913-469d-a4a5-4a805dcf158a),但它仍提示用户输入凭据,因为在返回的内容中有指向安全物品。
我有一个NetworkCredential对象,我非常想将其应用于所进行的每个HTTP调用。
当然一定有人做过吗?:)
impersonation networkcredentials windows-8 dotnet-httpclient winrt-xaml
我有一个方法尝试从并行的几个URL下载数据,并返回一个IEnumerable反序列化类型
该方法如下所示:
public IEnumerable<TContent> DownloadContentFromUrls(IEnumerable<string> urls)
{
var list = new List<TContent>();
Parallel.ForEach(urls, url =>
{
lock (list)
{
_httpClient.GetAsync(url).ContinueWith(request =>
{
var response = request.Result;
//todo ensure success?
response.Content.ReadAsStringAsync().ContinueWith(text =>
{
var results = JObject.Parse(text.Result)
.ToObject<IEnumerable<TContent>>();
list.AddRange(results);
});
});
}
});
return list;
}
Run Code Online (Sandbox Code Playgroud)
在我的单元测试中(我存根_httpClient返回一组已知的文本)我基本上得到了
序列不包含任何元素
这是因为该方法在任务完成之前返回.
如果我在.ContinueWith()调用结束时添加.Wait(),它会通过,但我确定我在这里滥用了API ...
c# asynchronous task-parallel-library async-await dotnet-httpclient
我想在C#中使用sonicAPI文件/上传API.
我尝试将curl示例转换为C#with HttpClient并MultipartFormDataContent返回错误400 /错误请求.
回复内容:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status code="400" />
<errors>
<error message="File upload failed: file is missing." parameter="file" error_code="10" />
</errors>
</response>
Run Code Online (Sandbox Code Playgroud)
文档中显示的curl命令行示例:
curl https://api.sonicapi.com/file/upload?access_id=$ACCESS_ID -Ffile=@Vocals.mp3
到目前为止我编写的代码:
public async Task<HttpResponseMessage> Post(string id, string fileName)
{
string url = string.Format("http://api.sonicapi.com/file/upload?access_id={0}", id);
var stream = new FileStream(fileName, FileMode.Open);
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
var content = new MultipartFormDataContent();
content.Add(new StreamContent(stream), "file");
HttpResponseMessage message = await client.PostAsync(url, content); …Run Code Online (Sandbox Code Playgroud) 我正在使用.NET HttpClient向我的服务器发送请求.我已将HttpClient.Timeout属性设置为10秒,因此A task was cancelled每当服务器无法在不到10秒的时间内处理我的请求时,我就会收到异常.好到这里.
但是,如果关闭服务器,则需要HttpClient大约20秒才能返回正确的异常,例如图片中的异常.
我想看到这个异常超过10秒才能区分Server Down和Operation花了太长时间的情况.我在msdn文档中找不到任何相关内容.是否有可以设置的超时HttpClient?
这是我如何构建的 HttpClient
var webRequestHandler = new WebRequestHandler
{
UseProxy = false,
Proxy = null,
AllowPipelining = false,
ContinueTimeout = TimeSpan.Zero,
UseCookies = false,
AllowAutoRedirect = false,
};
var httpClient = new HttpClient(webRequestHandler);
httpClient.Timeout = timeout;
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgent);
httpClient.DefaultRequestHeaders.ExpectContinue = false;
Run Code Online (Sandbox Code Playgroud) 我System.net.http在Windows Phone 8.1应用程序中使用,直到遇到自签名和不受信任的证书问题.
那么现在,我正在使用Windows.Web.Http框架.一切都很好,除了我找不到ByteArrayContent与IHttpContent界面相同的东西.以同样的方式,IHttpContent没有相同的方法ReadAsByteArrayAsync.
我正在使用ByteArrayContent和ReadAsByteArrayAsync通过HttpClient发送和获取文件.
什么是正确的方法?
谢谢!
c# web-services bytearray dotnet-httpclient windows-phone-8.1
我正在尝试将一个调用包装到PostAsync,所以我不必在我的代码库中重新编码调用序列.我遇到的问题是我从调用中分配的HttpResponseMessage与我的方法调用的消费者不同.这是代码:
internal class RestHttpClient
{
public HttpResponseMessage ResponseMessage = new HttpResponseMessage();
public async void SendRequest(string adaptiveUri, string xmlRequest)
{
using (HttpClient httpClient = new HttpClient())
{
StringContent httpConent = new StringContent(xmlRequest, Encoding.UTF8);
try
{
ResponseMessage = await httpClient.PostAsync(adaptiveUri, httpConent);
}
catch (Exception ex)
{
ResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
ResponseMessage.ReasonPhrase = string.Format("RestHttpClient.SendRequest failed: {0}", ex);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图调用该方法如下:
RestHttpClient restHttpClient = new RestHttpClient();
restHttpClient.SendRequest(adaptiveUri, xmlRequest);
return restHttpClient.ResponseMessage;
Run Code Online (Sandbox Code Playgroud)
当我进行调用时,ResponseMessage对象始终包含Ok状态,即使这不是从PostAsync调用实际返回的内容.
情景:
首先,请考虑我正在使用HttpClient课程,不是WebRequest,我知道这里有很多相关问题,但所有答案都是针对WebRequest的.
我制作了一个Web Api应用程序,以这种方式设置以下标题,以便下载.txt文件:
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = _datacontext.GetAppConfig("814FileNameHeader") + DateTime.Now.ToString("yyyyMMdd") + ".txt"
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
Run Code Online (Sandbox Code Playgroud)
之后我从其他应用程序中创建了一个HttpClient来连接到这个方法.
一切正常,检索200和文件的内容.但我无法获取标题以读取文件名.
TRIES MADE:
使用REST客户端我可以阅读以下标头属性:
内容 - 处理:附件; 文件名= 814Entes_PG_20160114.txt
从代码我可以调试它,我发现标题是在"invalidHeaders",但我无法达到值:
题:
我如何设置这个并毫无疑问地从客户那里获得?
更新:
这些是我尝试获取标题:原始:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(uri);
string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
req.Content = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用dotnet核心应用程序中的WebAPI为请求指定Web代理.当我定位实际的clr(dnx46)时,这段代码曾经工作但是,现在我正在尝试使用rc2的东西,说支持的框架是netcoreapp1.0和netstandard1.5.
var clientHandler = new HttpClientHandler{
Proxy = string.IsNullOrWhiteSpace(this._clientSettings.ProxyUrl) ? null : new WebProxy (this._clientSettings.ProxyUrl, this._clientSettings.BypassProxyOnLocal),
UseProxy = !string.IsNullOrWhiteSpace(this._clientSettings.ProxyUrl)
};
Run Code Online (Sandbox Code Playgroud)
我想知道WebProxy类去了哪里.我无法在任何地方找到它,甚至在github存储库中也找不到它.如果它从WebProxy改变了,它改变了什么?我需要能够将代理设置为特定请求的特定URL,因此使用"全局Internet Explorer"方式不能满足我的需求.这主要用于调试Web请求/响应目的.
对于下面的代码,它在调用时捕获HttpRequestException/System.Net.Http.WinHttpException
异常状态:NativeErrorCode 12175
消息"发生安全性错误"
__CODE__1.ConfiguredTaskAwaiter.GetResult()at System.Net.Http.HttpClient.d__58.MoveNext()---从抛出异常的先前位置开始的堆栈跟踪结束---在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()在Controllers.Controller.d__0.MoveNext()的System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()上的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)但是在相同的端点,资源,标题和正文上使用Postman,我得到200回.
NativeErrorCode 12175
Message "A security error occurred"
- e {System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.Http.WinHttpException: A security error occurred
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at System.Net.Http.WinHttpHandler.<StartRequest>d__105.MoveNext()
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at System.Net.Http.HttpClient.<FinishSendAsync>d__58.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() …Run Code Online (Sandbox Code Playgroud) 我有Asp.Net Core WebApi。我正在根据HttpClientFactory模式发出Http请求。这是我的示例代码:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpClient<IMyInterface, MyService>();
...
}
public class MyService: IMyInterface
{
private readonly HttpClient _client;
public MyService(HttpClient client)
{
_client = client;
}
public async Task CallHttpEndpoint()
{
var request = new HttpRequestMessage(HttpMethod.Get, "www.customUrl.com");
var response = await _client.SendAsync(request);
...
}
}
Run Code Online (Sandbox Code Playgroud)
我想通过动态代理实现发送请求。这基本上意味着我可能需要针对每个请求更改代理。到目前为止,我发现了2种方法,对我来说似乎没有一种是好的:
1.有一个像这样的静态代理:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddHttpClient<IMyInterface, MyService>().ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = true
};
});
...
} …Run Code Online (Sandbox Code Playgroud) c# ×8
.net ×2
asp.net-core ×2
async-await ×2
asynchronous ×2
.net-core ×1
attachment ×1
bytearray ×1
coreclr ×1
curl ×1
http ×1
http-headers ×1
web-services ×1
windows-8 ×1
winrt-xaml ×1