本文整理汇总了C#中System.Net.Http.HttpRequestMessage.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage.Dispose方法的具体用法?C# HttpRequestMessage.Dispose怎么用?C# HttpRequestMessage.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetHobbits
public IEnumerable<Hobbit> GetHobbits()
{
string reasonPhrase;
using (var client = new HttpClient { BaseAddress = new Uri(BaseUri) })
{
var request = new HttpRequestMessage(HttpMethod.Get, "/api/hobbit");
request.Headers.Add("Accept", "application/json");
var response = client.SendAsync(request);
var content = response.Result.Content.ReadAsStringAsync().Result;
var status = response.Result.StatusCode;
reasonPhrase = response.Result.ReasonPhrase;
request.Dispose();
response.Dispose();
if (status == HttpStatusCode.OK)
{
return !string.IsNullOrEmpty(content) ?
JsonConvert.DeserializeObject<IEnumerable<Hobbit>>(content)
: null;
}
throw new Exception(reasonPhrase);
}
}
示例2: GetResponse
public static async Task<HttpResponseMessage> GetResponse(
string requestUri,
HttpMethod httpMethod,
HttpContent requestContent,
Action<HttpConfiguration, HttpServer> registerOData,
IEnumerable<KeyValuePair<string, string>> headers = null)
{
using (HttpConfiguration config = new HttpConfiguration())
{
using (HttpServer server = new HttpServer(config))
using (HttpMessageInvoker client = new HttpMessageInvoker(server))
{
registerOData(config, server);
HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri);
try
{
request.Content = requestContent;
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
return await client.SendAsync(request, CancellationToken.None);
}
finally
{
request.DisposeRequestResources();
request.Dispose();
}
}
}
}
示例3: GetAllEvents
public IEnumerable<Event> GetAllEvents()
{
string reasonPhrase;
using (var client = HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "/events");
request.Headers.Add("Accept", "application/json");
var response = client.SendAsync(request);
var result = response.Result;
var content = result.Content.ReadAsStringAsync().Result;
var status = result.StatusCode;
reasonPhrase = result.ReasonPhrase;
if (status == HttpStatusCode.OK)
{
return !String.IsNullOrEmpty(content)
? JsonConvert.DeserializeObject<IEnumerable<Event>>(content, _jsonSettings)
: new List<Event>();
}
request.Dispose();
response.Dispose();
result.Dispose();
}
throw new InvalidOperationException(reasonPhrase);
}
示例4: RunTest
public static void RunTest(string controllerName, string routeSuffix, HttpRequestMessage request,
Action<HttpResponseMessage> assert, Action<HttpConfiguration> configurer = null)
{
// Arrange
HttpConfiguration config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };
config.Routes.MapHttpRoute("Default", "{controller}" + routeSuffix, new { controller = controllerName });
if (configurer != null)
{
configurer(config);
}
HttpServer server = new HttpServer(config);
HttpMessageInvoker invoker = new HttpMessageInvoker(server);
HttpResponseMessage response = null;
try
{
// Act
response = invoker.SendAsync(request, CancellationToken.None).Result;
// Assert
assert(response);
}
finally
{
request.Dispose();
if (response != null)
{
response.Dispose();
}
}
}
示例5: GetThumbUrl
public string GetThumbUrl(News news)
{
var url = $"https://www.belstu.by/usdata/news/{news.GroupId}/{FsOptions.ThumbsFilename}";
var client = new HttpClient();
var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
var response = client.SendAsync(requestMessage);
var result = response.Result.Content.ReadAsStringAsync().Result;
response.Result.Dispose();
requestMessage.Dispose();
client.Dispose();
return result.Contains("404 | БГТУ") ? "" : url;
}
示例6: GetJsonAsync
public static async Task<JObject> GetJsonAsync(this IHttp This, HttpRequestMessage request)
{
HttpResponseMessage response = await This.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
throw new HttpStatusCodeException(response.StatusCode, error);
}
HttpContent responseContent = response.Content;
JObject result = await ResponseHelper.GetResponseAsJObject(responseContent);
// cleanup the request
request.Dispose();
response.Dispose();
return result;
}
示例7: Send
/// <summary>
/// Sends a <paramref name="request"/> using the given <paramref name="client"/>.
/// </summary>
/// <param name="client">The <see cref="HttpClient"/> on which to execute the request.</param>
/// <param name="eventLoop">The <see cref="EventLoop"/> on which to execute callbacks.</param>
/// <param name="request">The <see cref="HttpResponseMessage"/> which to send.</param>
/// <returns>Returns a <see cref="Promise{HttpResponseMessage}"/> resolving to <see cref="HttpResponseMessage"/>.</returns>
/// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception>
public static CancelablePromise<HttpResponseMessage> Send(this HttpClient client, EventLoop eventLoop, HttpRequestMessage request)
{
// validate arguments
if (client == null)
throw new ArgumentNullException("client");
if (eventLoop == null)
throw new ArgumentNullException("eventLoop");
if (request == null)
throw new ArgumentNullException("request");
// create the cancellation token
var cts = new CancellationTokenSource();
var token = cts.Token;
// create the deferred
var deferred = eventLoop.Defer<HttpResponseMessage>(cts.Cancel);
// create a resource managed by the event loop
eventLoop.TrackResource(token, Task.Run(() => {
try
{
// send the request and retrieve the response
var response = client.SendAsync(request, token).Result;
// resolve the deferred if not cancelled
if (!token.IsCancellationRequested)
deferred.Resolve(response);
}
catch (Exception ex)
{
// something bad happened, reject the deferred if not cancelled
if (!token.IsCancellationRequested)
deferred.Reject(ex);
}
// dispose the used resources
request.Dispose();
cts.Dispose();
}));
// return the promise
return deferred.Promise;
}
示例8: GetResponseWithContentValidation
public static async Task<HttpResponseMessage> GetResponseWithContentValidation(
string requestUri,
HttpMethod httpMethod,
HttpContent requestContent,
Action<HttpConfiguration, HttpServer> registerOData,
HttpStatusCode expectedStatusCode,
string baselineFileName,
Func<string, string> postProcessContentHandler = null,
IEnumerable<KeyValuePair<string, string>> headers = null)
{
using (HttpConfiguration config = new HttpConfiguration())
{
using (HttpServer server = new HttpServer(config))
using (HttpMessageInvoker client = new HttpMessageInvoker(server))
{
registerOData(config, server);
HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri);
try
{
request.Content = requestContent;
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
var response = await client.SendAsync(request, CancellationToken.None);
await CheckResponse(response, expectedStatusCode, baselineFileName, postProcessContentHandler);
return response;
}
finally
{
request.DisposeRequestResources();
request.Dispose();
}
}
}
}
示例9: IsAlive
public bool IsAlive()
{
using (var client = HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, "/stats/status");
var response = client.SendAsync(request);
var result = response.Result;
var content = result.Content.ReadAsStringAsync().Result;
var status = result.StatusCode;
if (status == HttpStatusCode.OK && content.Equals("alive"))
{
return true;
}
request.Dispose();
response.Dispose();
result.Dispose();
}
return false;
}
示例10: SendAsync
private async Task<HttpResponseMessage> SendAsync(Uri uri, List<KeyValuePair<string, string>> headers, string content, string httpMethod)
{
HttpClient client = (HttpClient)null;
HttpRequestMessage request = (HttpRequestMessage)null;
StringContent sc = (StringContent)null;
HttpResponseMessage httpResponseMessage1;
try
{
client = this.CreateClient();
if (headers != null)
{
foreach (KeyValuePair<string, string> keyValuePair in headers)
{
KeyValuePair<string, string> header = keyValuePair;
client.DefaultRequestHeaders.Add(header.Key, header.Value);
header = new KeyValuePair<string, string>();
}
//List<KeyValuePair<string, string>>.Enumerator enumerator = new List<KeyValuePair<string, string>>.Enumerator();
}
sc = new StringContent(content, Encoding.UTF8, "application/json");
HttpMethod method = new HttpMethod(httpMethod);
request = new HttpRequestMessage()
{
Content = (HttpContent)sc,
Method = method,
RequestUri = uri
};
HttpResponseMessage httpResponseMessage = await client.SendAsync(request);
HttpResponseMessage responseMessage = httpResponseMessage;
httpResponseMessage = (HttpResponseMessage)null;
httpResponseMessage1 = responseMessage;
}
finally
{
if (client != null)
client.Dispose();
if (request != null)
request.Dispose();
if (sc != null)
sc.Dispose();
}
return httpResponseMessage1;
}
示例11: ConvertResponse
/// <summary>
/// Converts a <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> and disposes the
/// <see cref="HttpResponseMessage"/> and <see cref="HttpRequestMessage"/> upon completion.
/// </summary>
/// <param name="httpContextBase">The HTTP context base.</param>
/// <param name="response">The response to convert.</param>
/// <param name="request">The request (which will be disposed).</param>
/// <returns>A <see cref="Task"/> representing the conversion of an <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/>
/// including writing out any entity body.</returns>
internal static Task ConvertResponse(HttpContextBase httpContextBase, HttpResponseMessage response, HttpRequestMessage request)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(response != null);
Contract.Assert(request != null);
HttpResponseBase httpResponseBase = httpContextBase.Response;
httpResponseBase.StatusCode = (int)response.StatusCode;
httpResponseBase.StatusDescription = response.ReasonPhrase;
httpResponseBase.TrySkipIisCustomErrors = true;
EnsureSuppressFormsAuthenticationRedirect(httpContextBase);
CopyHeaders(response.Headers, httpContextBase);
CacheControlHeaderValue cacheControl = response.Headers.CacheControl;
// TODO 335085: Consider this when coming up with our caching story
if (cacheControl == null)
{
// DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
// However, we don't want requests to be cached by default.
// If nobody set an explicit CacheControl then explicitly set to no-cache to override the
// default behavior. This will cause the following response headers to be emitted:
// Cache-Control: no-cache
// Pragma: no-cache
// Expires: -1
httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
Task responseTask = null;
bool isBuffered = false;
if (response.Content != null)
{
CopyHeaders(response.Content.Headers, httpContextBase);
// Select output buffering by the kind of content
isBuffered = IsOutputBufferingNecessary(response.Content);
httpResponseBase.BufferOutput = isBuffered;
responseTask = response.Content.CopyToAsync(httpResponseBase.OutputStream);
}
else
{
responseTask = TaskHelpers.Completed();
}
return responseTask
.Catch((info) =>
{
if (isBuffered)
{
// Failure during the CopyToAsync needs to stop any partial content from
// reaching the client. If it was during a buffered write, we will give
// them InternalServerError with zero-length content.
httpResponseBase.SuppressContent = true;
httpResponseBase.Clear();
httpResponseBase.ClearContent();
httpResponseBase.ClearHeaders();
httpResponseBase.StatusCode = (int)Net.HttpStatusCode.InternalServerError;
}
else
{
// Any failure in non-buffered mode has already written out StatusCode and possibly content.
// This means the client will receive an OK but the content is incomplete.
// The proper action here is to abort the connection, but HttpResponse.Abort is a 4.5 feature.
// TODO: DevDiv bug #381233 -- call HttpResponse.Abort when it becomes available
httpResponseBase.Close();
}
// We do not propagate any errors up, or we will get the
// standard ASP.NET html page. We want empty content or
// a closed connection.
return info.Handled();
})
.Finally(
() =>
{
request.DisposeRequestResources();
request.Dispose();
response.Dispose();
});
}
示例12: ConvertResponse
/// <summary>
/// Converts a <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/> and disposes the
/// <see cref="HttpResponseMessage"/> and <see cref="HttpRequestMessage"/> upon completion.
/// </summary>
/// <param name="httpContextBase">The HTTP context base.</param>
/// <param name="response">The response to convert.</param>
/// <param name="request">The request (which will be disposed).</param>
/// <returns>A <see cref="Task"/> representing the conversion of an <see cref="HttpResponseMessage"/> to an <see cref="HttpResponseBase"/>
/// including writing out any entity body.</returns>
internal static async Task ConvertResponse(HttpContextBase httpContextBase, HttpResponseMessage response, HttpRequestMessage request)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(request != null);
// A null response creates a 500 with no content
if (response == null)
{
CreateEmptyErrorResponse(httpContextBase.Response);
return;
}
CopyResponseStatusAndHeaders(httpContextBase, response);
// TODO 335085: Consider this when coming up with our caching story
if (response.Headers.CacheControl == null)
{
// DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
// However, we don't want requests to be cached by default.
// If nobody set an explicit CacheControl then explicitly set to no-cache to override the
// default behavior. This will cause the following response headers to be emitted:
// Cache-Control: no-cache
// Pragma: no-cache
// Expires: -1
httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
// Asynchronously write the response body. If there is no body, we use
// a completed task to share the Finally() below.
// The response-writing task will not fault -- it handles errors internally.
try
{
if (response.Content != null)
{
await WriteResponseContentAsync(httpContextBase, response, request);
}
}
finally
{
request.DisposeRequestResources();
request.Dispose();
response.Dispose();
}
}
示例13: Main
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
var isUnix = Environment.OSVersion.Platform == PlatformID.Unix;
var hostsPath = isUnix ? "/etc/hosts" : [email protected]"{Environment.SystemDirectory}\drivers\etc\hosts";
Title = "Netsh.org Hosts Fetcher";
Clear();
#if !DEBUG
WriteLine("Warning: Educational Purpose Only!", Yellow);
Thread.Sleep(3000);
Clear();
WriteLine("Warning: Personal Use Only!", Yellow);
Thread.Sleep(3000);
Clear();
#endif
try
{
var localVersion = Regex.Match(File.ReadAllText(hostsPath), @"^# Current Version (.+)$", RegexOptions.Multiline).Groups[1].Value.Trim();
WriteLine($"Local hosts version: {(string.IsNullOrEmpty(localVersion) ? "not found" : localVersion)}");
}
catch (UnauthorizedAccessException)
{
WriteLine("Access denied, failed to read local hosts version.", Red);
}
var client = new HttpClient(new HttpClientHandler { UseCookies = false });
WriteLine("Fetching information.", Green);
WriteLine("HTTP GET https://serve.netsh.org/pub/ipv4-hosts/");
var mainPage = client.GetStringAsync("https://serve.netsh.org/pub/ipv4-hosts/").Result;
var passcode = Regex.Match(mainPage, @"pass = (\d+)").Groups[1].Value;
var validate = Regex.Match(mainPage, @"validate = ""(\w+)""").Groups[1].Value;
var doc = new HtmlDocument();
doc.LoadHtml(mainPage);
var info = doc.DocumentNode.QuerySelector(".version").ParentNode;
var branches = info.ChildNodes[0].InnerText.Split('/').ToList();
var version = branches[0];
branches = branches.Skip(1).Concat(new List<string> { "none" }).ToList();
var date = info.ChildNodes[1].InnerText;
var releaseNotes = info.ChildNodes[2].InnerText.Trim();
var switches = doc.DocumentNode.QuerySelectorAll("kuppy-checkbox, .kuppy-switch").Select(node => node.Attributes["for"].Value).Select(@switch => $"{@switch}=on").ToList();
WriteLine($"Current version: {version}");
WriteLine($"Release date: {date}");
WriteLine($"Release notes: {releaseNotes}");
string branch;
SelectBranch:
ForegroundColor = Yellow;
WriteLine($"Enter branch name({string.Join("/", branches)}):");
branch = ReadLine().Trim().ToLower();
ResetColor();
if (!branches.Exists(item => item == branch))
{
WriteLine("Invalid choice!", Red);
goto SelectBranch;
}
WriteLine("Fetching hosts.", Green);
var url = $"https://serve.netsh.org/pub/ipv4-hosts/collection/{branch}.php?{string.Join("&", switches)}&passcode={passcode}&validate={validate}";
WriteLine($"HTTP GET {url}");
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Referrer = new Uri("https://serve.netsh.org/pub/");
message.Headers.Add("Cookie", $"hostspasscode={passcode}");
message.Headers.Host = "serve.netsh.org";
var hosts = client.SendAsync(message).Result.Content.ReadAsStringAsync().Result;
message.Dispose();
client.Dispose();
WriteLine("Processing text.", Green);
hosts = hosts.Replace("\n", Environment.NewLine);
if (isUnix) hosts = $"127.0.0.1 {Environment.MachineName}{Environment.NewLine}{hosts}";
var fileName = $"hosts-{branch}-{DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss")}";
WriteLine($"Writing output file: {fileName}.", Green);
File.WriteAllText(fileName, hosts);
OverrideFile:
WriteLine("Override current hosts file?(y/n):", Yellow);
ForegroundColor = Yellow;
string choice = ReadLine().Trim().ToLower();
ResetColor();
if (choice == "y")
{
try
{
File.Copy(fileName, hostsPath, true);
WriteLine("Succeeded", Green);
}
catch (UnauthorizedAccessException)
{
WriteLine("Access denied, please run the program as administrator!", Red);
}
}
else if (choice != "n")
{
WriteLine("Invalid choice!", Red);
goto OverrideFile;
//.........这里部分代码省略.........
示例14: ListNamesAsync
//.........这里部分代码省略.........
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json;odata.metadata=none");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
IndexListNamesResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new IndexListNamesResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.IndexNames.Add(nameInstance);
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
示例15: GetEventById
public Event GetEventById(Guid id)
{
string reasonPhrase;
using (var client = HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, String.Format("/events/{0}", id));
request.Headers.Add("Accept", "application/json");
var response = client.SendAsync(request);
var result = response.Result;
var content = result.Content.ReadAsStringAsync().Result;
var status = result.StatusCode;
reasonPhrase = result.ReasonPhrase;
if (status == HttpStatusCode.OK)
{
return JsonConvert.DeserializeObject<Event>(content, _jsonSettings);
}
request.Dispose();
response.Dispose();
result.Dispose();
}
throw new InvalidOperationException(reasonPhrase);
}