本文整理汇总了C#中System.Net.Http.WinHttpRequestState类的典型用法代码示例。如果您正苦于以下问题:C# WinHttpRequestState类的具体用法?C# WinHttpRequestState怎么用?C# WinHttpRequestState使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WinHttpRequestState类属于System.Net.Http命名空间,在下文中一共展示了WinHttpRequestState类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ResetCookieRequestHeaders
public static void ResetCookieRequestHeaders(WinHttpRequestState state, Uri redirectUri)
{
SafeWinHttpHandle requestHandle = state.RequestHandle;
Debug.Assert(state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer);
// Clear cookies.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
CookieHeaderNameWithColon,
(uint)CookieHeaderNameWithColon.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_REPLACE))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
// Re-add cookies. The GetCookieHeader() method will return the correct set of
// cookies based on the redirectUri.
string cookieHeader = GetCookieHeader(redirectUri, state.Handler.CookieContainer);
if (!string.IsNullOrEmpty(cookieHeader))
{
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
requestHandle,
cookieHeader,
(uint)cookieHeader.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
}
示例2: AddResponseCookiesToContainer
public static void AddResponseCookiesToContainer(WinHttpRequestState state)
{
HttpRequestMessage request = state.RequestMessage;
SafeWinHttpHandle requestHandle = state.RequestHandle;
CookieContainer cookieContainer = state.Handler.CookieContainer;
Debug.Assert(state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer);
Debug.Assert(cookieContainer != null);
// Get 'Set-Cookie' headers from response.
List<string> cookieHeaders =
WinHttpResponseParser.GetResponseHeaders(requestHandle, Interop.WinHttp.WINHTTP_QUERY_SET_COOKIE);
WinHttpTraceHelper.Trace("WINHTTP_QUERY_SET_COOKIE");
foreach (string cookieHeader in cookieHeaders)
{
WinHttpTraceHelper.Trace(cookieHeader);
try
{
cookieContainer.SetCookies(request.RequestUri, cookieHeader);
WinHttpTraceHelper.Trace(cookieHeader);
}
catch (CookieException)
{
// We ignore malformed cookies in the response.
WinHttpTraceHelper.Trace("Ignoring invalid cookie: {0}", cookieHeader);
}
}
}
示例3: RequestCallback
private static void RequestCallback(
IntPtr handle,
WinHttpRequestState state,
uint internetStatus,
IntPtr statusInformation,
uint statusInformationLength)
{
try
{
switch (internetStatus)
{
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
OnRequestSendRequestComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
OnRequestReadComplete(state, statusInformationLength);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
OnRequestWriteComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
OnRequestReceiveResponseHeadersComplete(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REDIRECT:
string redirectUriString = Marshal.PtrToStringUni(statusInformation);
var redirectUri = new Uri(redirectUriString);
OnRequestRedirect(state, redirectUri);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
OnRequestSendingRequest(state);
return;
case Interop.WinHttp.WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
Debug.Assert(
statusInformationLength == Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(),
"RequestCallback: statusInformationLength=" + statusInformationLength +
" must be sizeof(WINHTTP_ASYNC_RESULT)=" + Marshal.SizeOf<Interop.WinHttp.WINHTTP_ASYNC_RESULT>());
var asyncResult = Marshal.PtrToStructure<Interop.WinHttp.WINHTTP_ASYNC_RESULT>(statusInformation);
OnRequestError(state, asyncResult);
return;
default:
return;
}
}
catch (Exception ex)
{
Interop.WinHttp.WinHttpCloseHandle(handle);
state.SavedException = ex;
}
}
示例4: WinHttpRequestStream
internal WinHttpRequestStream(WinHttpRequestState state, bool chunkedMode)
{
_state = state;
_chunkedMode = chunkedMode;
}
示例5: SendAsync
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
#endif
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
// Check for invalid combinations of properties.
if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy)
{
throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy);
}
if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null)
{
throw new InvalidOperationException(SR.net_http_invalid_proxy);
}
if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer &&
_cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request);
SetOperationStarted();
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
// Create state object and save current values of handler settings.
var state = new WinHttpRequestState();
state.Tcs = tcs;
state.CancellationToken = cancellationToken;
state.RequestMessage = request;
state.Handler = this;
state.CheckCertificateRevocationList = _checkCertificateRevocationList;
state.ServerCertificateValidationCallback = _serverCertificateValidationCallback;
state.WindowsProxyUsePolicy = _windowsProxyUsePolicy;
state.Proxy = _proxy;
state.ServerCredentials = _serverCredentials;
state.DefaultProxyCredentials = _defaultProxyCredentials;
state.PreAuthenticate = _preAuthenticate;
Task.Factory.StartNew(
s => {
var whrs = (WinHttpRequestState)s;
whrs.Handler.StartRequest(whrs);
},
state,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
s_diagnosticListener.LogHttpResponse(tcs.Task, loggingRequestId);
return tcs.Task;
}
示例6: OnRequestRedirect
private static void OnRequestRedirect(WinHttpRequestState state, Uri redirectUri)
{
const string EmptyCookieHeader = "Cookie:";
Debug.Assert(state != null, "OnRequestRedirect: state is null");
Debug.Assert(redirectUri != null, "OnRequestRedirect: redirectUri is null");
Debug.Assert(state.TcsReceiveResponseHeaders != null, "TcsReceiveResponseHeaders is null");
Debug.Assert(!state.TcsReceiveResponseHeaders.Task.IsCompleted, "TcsReceiveResponseHeaders.Task is completed");
// If we're manually handling cookies, we need to reset them based on the new URI.
if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
// Clear cookies.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
state.RequestHandle,
EmptyCookieHeader,
(uint)EmptyCookieHeader.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_REPLACE))
{
int lastError = Marshal.GetLastWin32Error();
if (lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
throw WinHttpException.CreateExceptionUsingError(lastError);
}
}
// Re-add cookies. The GetCookieHeader() method will return the correct set of
// cookies based on the redirectUri.
string cookieHeader = WinHttpHandler.GetCookieHeader(redirectUri, state.Handler.CookieContainer);
if (!string.IsNullOrEmpty(cookieHeader))
{
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
state.RequestHandle,
cookieHeader,
(uint)cookieHeader.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
}
state.RequestMessage.RequestUri = redirectUri;
// Redirection to a new uri may require a new connection through a potentially different proxy.
// If so, we will need to respond to additional 407 proxy auth demands and re-attach any
// proxy credentials. The ProcessResponse() method looks at the state.LastStatusCode
// before attaching proxy credentials and marking the HTTP request to be re-submitted.
// So we need to reset the LastStatusCode remembered. Otherwise, it will see additional 407
// responses as an indication that proxy auth failed and won't retry the HTTP request.
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
state.LastStatusCode = 0;
}
// For security reasons, we drop the server credential if it is a
// NetworkCredential. But we allow credentials in a CredentialCache
// since they are specifically tied to URI's.
if (!(state.ServerCredentials is CredentialCache))
{
state.ServerCredentials = null;
}
}
示例7: OnRequestError
private static void OnRequestError(WinHttpRequestState state, Interop.WinHttp.WINHTTP_ASYNC_RESULT asyncResult)
{
WinHttpTraceHelper.TraceAsyncError("OnRequestError", asyncResult);
Debug.Assert(state != null, "OnRequestError: state is null");
var innerException = WinHttpException.CreateExceptionUsingError((int)asyncResult.dwError);
switch ((uint)asyncResult.dwResult.ToInt32())
{
case Interop.WinHttp.API_SEND_REQUEST:
state.TcsSendRequest.TrySetException(innerException);
break;
case Interop.WinHttp.API_RECEIVE_RESPONSE:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_RESEND_REQUEST)
{
state.RetryRequest = true;
state.TcsReceiveResponseHeaders.TrySetResult(false);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED)
{
// WinHttp will automatically drop any client SSL certificates that we
// have pre-set into the request handle including the NULL certificate
// (which means we have no certs to send). For security reasons, we don't
// allow the certificate to be re-applied. But we need to tell WinHttp
// explicitly that we don't have any certificate to send.
WinHttpHandler.SetNoClientCertificate(state.RequestHandle);
state.RetryRequest = true;
state.TcsReceiveResponseHeaders.TrySetResult(false);
}
else if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
state.TcsReceiveResponseHeaders.TrySetCanceled(state.CancellationToken);
}
else
{
state.TcsReceiveResponseHeaders.TrySetException(innerException);
}
break;
case Interop.WinHttp.API_READ_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsReadFromResponseStream.TrySetCanceled();
}
else
{
state.TcsReadFromResponseStream.TrySetException(
new IOException(SR.net_http_io_read, innerException));
}
break;
case Interop.WinHttp.API_WRITE_DATA:
if (asyncResult.dwError == Interop.WinHttp.ERROR_WINHTTP_OPERATION_CANCELLED)
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's WriteAsync() call into the TrySetCanceled().
Debug.WriteLine("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsInternalWriteDataToRequestStream.TrySetCanceled();
}
else
{
state.TcsInternalWriteDataToRequestStream.TrySetException(
new IOException(SR.net_http_io_write, innerException));
}
break;
default:
Debug.Fail(
"OnRequestError: Result (" + asyncResult.dwResult + ") is not expected.",
"Error code: " + asyncResult.dwError + " (" + innerException.Message + ")");
break;
}
}
示例8: OnRequestSendRequestComplete
private static void OnRequestSendRequestComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestSendRequestComplete: state is null");
Debug.Assert(state.TcsSendRequest != null, "OnRequestSendRequestComplete: TcsSendRequest is null");
Debug.Assert(!state.TcsSendRequest.Task.IsCompleted, "OnRequestSendRequestComplete: TcsSendRequest.Task is completed");
state.TcsSendRequest.TrySetResult(true);
}
示例9: OnRequestWriteComplete
private static void OnRequestWriteComplete(WinHttpRequestState state)
{
Debug.Assert(state != null, "OnRequestWriteComplete: state is null");
Debug.Assert(state.TcsInternalWriteDataToRequestStream != null, "TcsInternalWriteDataToRequestStream is null");
Debug.Assert(!state.TcsInternalWriteDataToRequestStream.Task.IsCompleted, "TcsInternalWriteDataToRequestStream.Task is completed");
state.TcsInternalWriteDataToRequestStream.TrySetResult(true);
}
示例10: InternalSendRequestAsync
private Task<bool> InternalSendRequestAsync(WinHttpRequestState state)
{
state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
lock (state.Lock)
{
if (!Interop.WinHttp.WinHttpSendRequest(
state.RequestHandle,
null,
0,
IntPtr.Zero,
0,
0,
state.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return state.TcsSendRequest.Task;
}
示例11: SetRequestHandleOptions
private void SetRequestHandleOptions(WinHttpRequestState state)
{
SetRequestHandleProxyOptions(state);
SetRequestHandleDecompressionOptions(state.RequestHandle);
SetRequestHandleRedirectionOptions(state.RequestHandle);
SetRequestHandleCookieOptions(state.RequestHandle);
SetRequestHandleTlsOptions(state.RequestHandle);
SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri);
SetRequestHandleCredentialsOptions(state);
SetRequestHandleBufferingOptions(state.RequestHandle);
SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version);
}
示例12: CreateResponseMessage
public static HttpResponseMessage CreateResponseMessage(
WinHttpRequestState state,
bool doManualDecompressionCheck)
{
HttpRequestMessage request = state.RequestMessage;
SafeWinHttpHandle requestHandle = state.RequestHandle;
CookieUsePolicy cookieUsePolicy = state.Handler.CookieUsePolicy;
CookieContainer cookieContainer = state.Handler.CookieContainer;
var response = new HttpResponseMessage();
bool stripEncodingHeaders = false;
// Get HTTP version, status code, reason phrase from the response headers.
string version = GetResponseHeaderStringInfo(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION);
if (string.Compare("HTTP/1.1", version, StringComparison.OrdinalIgnoreCase) == 0)
{
response.Version = HttpVersion.Version11;
}
else if (string.Compare("HTTP/1.0", version, StringComparison.OrdinalIgnoreCase) == 0)
{
response.Version = HttpVersion.Version10;
}
else
{
response.Version = HttpVersion.Unknown;
}
response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE);
response.ReasonPhrase = GetResponseHeaderStringInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT);
// Create response stream and wrap it in a StreamContent object.
var responseStream = new WinHttpResponseStream(state);
Stream decompressedStream = responseStream;
if (doManualDecompressionCheck)
{
string contentEncoding = GetResponseHeaderStringInfo(
requestHandle,
Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING);
if (!string.IsNullOrEmpty(contentEncoding))
{
if (contentEncoding.IndexOf(EncodingNameDeflate, StringComparison.OrdinalIgnoreCase) > -1)
{
decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
else if (contentEncoding.IndexOf(EncodingNameGzip, StringComparison.OrdinalIgnoreCase) > -1)
{
decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress);
stripEncodingHeaders = true;
}
}
}
var content = new StreamContent(decompressedStream);
response.Content = content;
response.RequestMessage = request;
// Parse raw response headers and place them into response message.
ParseResponseHeaders(requestHandle, response, stripEncodingHeaders);
// Store response header cookies into custom CookieContainer.
if (cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer)
{
Debug.Assert(cookieContainer != null);
if (response.Headers.Contains(HeaderNameSetCookie))
{
IEnumerable<string> cookieHeaders = response.Headers.GetValues(HeaderNameSetCookie);
foreach (var cookieHeader in cookieHeaders)
{
try
{
cookieContainer.SetCookies(request.RequestUri, cookieHeader);
}
catch (CookieException)
{
// We ignore malformed cookies in the response.
}
}
}
}
return response;
}
示例13: SetRequestHandleCredentialsOptions
private void SetRequestHandleCredentialsOptions(WinHttpRequestState state)
{
// Set WinHTTP to send/prevent default credentials for either proxy or server auth.
bool useDefaultCredentials = false;
if (state.ServerCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.WindowsProxyUsePolicy != WindowsProxyUsePolicy.DoNotUseProxy)
{
if (state.Proxy == null && _defaultProxyCredentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
else if (state.Proxy != null && state.Proxy.Credentials == CredentialCache.DefaultCredentials)
{
useDefaultCredentials = true;
}
}
uint optionData = useDefaultCredentials ?
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_AUTOLOGON_POLICY, ref optionData);
}
示例14: WinHttpResponseStream
internal WinHttpResponseStream(WinHttpRequestState state)
{
_state = state;
}
示例15: CheckResponseForAuthentication
public void CheckResponseForAuthentication(
WinHttpRequestState state,
ref uint proxyAuthScheme,
ref uint serverAuthScheme)
{
uint supportedSchemes = 0;
uint firstSchemeIgnored = 0;
uint authTarget = 0;
Uri uri = state.RequestMessage.RequestUri;
state.RetryRequest = false;
// Check the status code and retry the request applying credentials if needed.
var statusCode = (HttpStatusCode)WinHttpResponseParser.GetResponseHeaderNumberInfo(
state.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE);
switch (statusCode)
{
case HttpStatusCode.Unauthorized:
if (state.ServerCredentials == null || state.LastStatusCode == HttpStatusCode.Unauthorized)
{
// Either we don't have server credentials or we already tried
// to set the credentials and it failed before.
// So we will let the 401 be the final status code returned.
break;
}
state.LastStatusCode = statusCode;
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
// We pass the schemes to ChooseAuthScheme which will pick the scheme
// based on most secure scheme to least secure scheme ordering.
if (!Interop.WinHttp.WinHttpQueryAuthSchemes(
state.RequestHandle,
out supportedSchemes,
out firstSchemeIgnored,
out authTarget))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// WinHTTP returns the proper authTarget based on the status code (401, 407).
// But we can validate with assert.
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
serverAuthScheme = ChooseAuthScheme(supportedSchemes);
if (serverAuthScheme != 0)
{
SetWinHttpCredential(
state.RequestHandle,
state.ServerCredentials,
uri,
serverAuthScheme,
authTarget);
state.RetryRequest = true;
}
break;
case HttpStatusCode.ProxyAuthenticationRequired:
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
// We tried already to set the credentials.
break;
}
state.LastStatusCode = statusCode;
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
// We pass the schemes to ChooseAuthScheme which will pick the scheme
// based on most secure scheme to least secure scheme ordering.
if (!Interop.WinHttp.WinHttpQueryAuthSchemes(
state.RequestHandle,
out supportedSchemes,
out firstSchemeIgnored,
out authTarget))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// WinHTTP returns the proper authTarget based on the status code (401, 407).
// But we can validate with assert.
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY);
proxyAuthScheme = ChooseAuthScheme(supportedSchemes);
state.RetryRequest = true;
break;
default:
if (state.PreAuthenticate && serverAuthScheme != 0)
{
SaveServerCredentialsToCache(uri, serverAuthScheme, state.ServerCredentials);
}
break;
}
}