本文整理汇总了C#中System.Net.Http.HttpRequestMessage类的典型用法代码示例。如果您正苦于以下问题:C# HttpRequestMessage类的具体用法?C# HttpRequestMessage怎么用?C# HttpRequestMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpRequestMessage类属于System.Net.Http命名空间,在下文中一共展示了HttpRequestMessage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ChangeUserProfile
public static async Task<bool> ChangeUserProfile(String name, String url, String description, String location,
UserAccountEntity userAccountEntity)
{
if (userAccountEntity.GetAccessToken().Equals("refresh"))
{
await Auth.RefreshAccessToken(userAccountEntity);
}
var param = new Dictionary<String, String>();
if (!string.IsNullOrEmpty(name)) param.Add("name", name);
if (!string.IsNullOrEmpty(url)) param.Add("url", url);
if (!string.IsNullOrEmpty(location)) param.Add("location", location);
if (!string.IsNullOrEmpty(description)) param.Add("description", description);
var theAuthClient = new HttpClient();
HttpContent header = new FormUrlEncodedContent(param);
var request = new HttpRequestMessage(HttpMethod.Post, EndPoints.ACCOUNT_UPDATE) {Content = header};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", userAccountEntity.GetAccessToken());
try
{
HttpResponseMessage response = await theAuthClient.SendAsync(request);
return response.IsSuccessStatusCode;
}
catch (Exception)
{
return false;
}
}
示例2: SendAsync
protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
if (HttpContext.Current.User.Identity.IsAuthenticated) {
return await base.SendAsync(request, cancellationToken);
}
if (!CanHandleAuthentication(request)) {
return await base.SendAsync(request, cancellationToken);
}
bool isAuthenticated;
try {
isAuthenticated = Authenticate(request);
}
catch (Exception) {
return CreateUnauthorizedResponse();
}
if (isAuthenticated) {
var response = await base.SendAsync(request, cancellationToken);
// add token cookie value
IEnumerable<CookieHeaderValue> ccoll = new CookieHeaderValue[] { new CookieHeaderValue(_TokenName, _Token) };
response.Headers.AddCookies(ccoll);
return response.StatusCode == HttpStatusCode.Unauthorized ? CreateUnauthorizedResponse() : response;
}
return CreateUnauthorizedResponse();
}
示例3: AppendAuthenticationHeader_ExpiredAccountSession
public async Task AppendAuthenticationHeader_ExpiredAccountSession()
{
var cachedAccountSession = new AccountSession
{
AccessToken = "token",
};
this.authenticationProvider.CurrentAccountSession = cachedAccountSession;
using (var httpRequestMessage = new HttpRequestMessage())
{
try
{
await this.authenticationProvider.AppendAuthHeaderAsync(httpRequestMessage);
}
catch (OneDriveException oneDriveException)
{
Assert.AreEqual(OneDriveErrorCode.AuthenticationFailure.ToString(), oneDriveException.Error.Code, "Unexpected error code.");
Assert.AreEqual(
"Failed to retrieve a valid authentication token for the user.",
oneDriveException.Error.Message,
"Unexpected error message.");
throw;
}
}
}
示例4: Translate
public string Translate(string text, string from, string to)
{
using (var client = new HttpClient())
{
var url = string.Format(
_translatorApiUrlFormat,
HttpUtility.UrlEncode(text),
HttpUtility.UrlEncode(from),
HttpUtility.UrlEncode(to));
using (var message = new HttpRequestMessage(HttpMethod.Get, url))
{
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetAccessToken());
using (var result = client.SendAsync(message).Result)
{
if (!result.IsSuccessStatusCode)
{
throw new TrosiTranslationException(result.Content.ReadAsStringAsync().Result);
}
using (var responseStream = result.Content.ReadAsStreamAsync().Result)
{
var serializer = new DataContractSerializer(typeof(string));
return serializer.ReadObject(responseStream) as string;
}
}
}
}
}
示例5: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
var url = new Java.Net.URL(java_uri);
var body = default(RequestBody);
if (request.Content != null) {
var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
body = RequestBody.Create(MediaType.Parse(request.Content.Headers.ContentType.MediaType), bytes);
}
var builder = new Request.Builder()
.Method(request.Method.Method.ToUpperInvariant(), body)
.Url(url);
var keyValuePairs = request.Headers
.Union(request.Content != null ?
(IEnumerable<KeyValuePair<string, IEnumerable<string>>>)request.Content.Headers :
Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());
foreach (var kvp in keyValuePairs) builder.AddHeader(kvp.Key, String.Join(",", kvp.Value));
cancellationToken.ThrowIfCancellationRequested();
var rq = builder.Build();
var call = client.NewCall(rq);
cancellationToken.Register(() => call.Cancel());
var resp = default(Response);
try {
resp = await call.EnqueueAsync().ConfigureAwait(false);
} catch (IOException ex) {
if (ex.Message.ToLowerInvariant().Contains("canceled")) {
throw new OperationCanceledException();
}
throw;
}
var respBody = resp.Body();
cancellationToken.ThrowIfCancellationRequested();
var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
if (respBody != null) {
var content = new ProgressStreamContent(respBody.ByteStream(), cancellationToken);
content.Progress = getAndRemoveCallbackFromRegister(request);
ret.Content = content;
} else {
ret.Content = new ByteArrayContent(new byte[0]);
}
var respHeaders = resp.Headers();
foreach (var k in respHeaders.Names()) {
ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
}
return ret;
}
示例6: AttriubteRouting_SelectsExpectedControllerAndAction
[InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
string expectedResult)
{
// Arrange
CustomersModelWithInheritance model = new CustomersModelWithInheritance();
var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
config.Services.Replace(typeof(IAssembliesResolver), resolver);
config.MapODataServiceRoute("odata", "", model.Model);
HttpServer server = new HttpServer(config);
config.EnsureInitialized();
HttpClient client = new HttpClient(server);
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);
// Act
var response = await client.SendAsync(request);
// Assert
if (!response.IsSuccessStatusCode)
{
Assert.False(true, await response.Content.ReadAsStringAsync());
}
var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
Assert.Equal(expectedResult, result.Value);
}
示例7: MessageHandler
private bool MessageHandler(HttpRequestMessage request, HttpResponseMessage response)
{
if (request.RequestUri.OriginalString.Contains("status"))
{
try
{
int code =
Convert.ToInt32(
request.RequestUri.OriginalString.Substring(request.RequestUri.OriginalString.Length - 3, 3));
HttpStatusCode status = (HttpStatusCode)code;
throw new HttpStatusException(status);
}
catch (HttpStatusException)
{
throw;
}
catch (Exception)
{
throw new HttpStatusException(HttpStatusCode.BadRequest);
}
}
else
response.Content = new StringContent(string.Format(Html, DateTime.Now.ToString("s"), request.RequestUri.OriginalString), Encoding.UTF8, "text/html");
return true;
}
示例8: Put
public HttpResponseMessage Put(HttpRequestMessage request, int betId, int userId, [FromBody]BetUser betUser)
{
if (!ModelState.IsValid)
{
return request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
}
if (betId != betUser.BetId || userId != betUser.UserId)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
}
try
{
this.dataService.UpdateBetUser(betUser);
}
catch (DbUpdateConcurrencyException)
{
if (this.dataService.GetBetUser(betId, userId) == null)
{
return request.CreateResponse(HttpStatusCode.NotFound);
}
else
{
throw;
}
}
//seriallize the object
return request.CreateResponse<BetUser>(HttpStatusCode.OK, betUser);
}
示例9: GetSuggestion
public HttpResponseMessageWrapper<Suggestion> GetSuggestion(HttpRequestMessage req, Guid id)
{
Operation operation = null;
HttpStatusCode code = AuthenticateUser(req);
if (code != HttpStatusCode.OK)
{ // user not authenticated
return ReturnResult<Suggestion>(req, operation, code);
}
try
{
Suggestion suggestion = this.SuggestionsStorageContext.Suggestions.Single<Suggestion>(s => s.ID == id);
if (!ValidateEntityOwnership(suggestion.EntityID, suggestion.EntityType))
{ // entity associated with suggestions does not belong to the authenticated user, return 403 Forbidden
TraceLog.TraceError("Associated entity does not belong to current user)");
return ReturnResult<Suggestion>(req, operation, HttpStatusCode.Forbidden);
}
var response = ReturnResult<Suggestion>(req, operation, suggestion, HttpStatusCode.OK);
response.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = true };
return response;
}
catch (Exception ex)
{ // suggestion not found - return 404 Not Found
TraceLog.TraceException("Resource not found", ex);
return ReturnResult<Suggestion>(req, operation, HttpStatusCode.NotFound);
}
}
示例10: SendRequestAsync_ReturnsSingleErrorResponse
public void SendRequestAsync_ReturnsSingleErrorResponse()
{
HttpRequestMessage[] requests = new HttpRequestMessage[]
{
new HttpRequestMessage(HttpMethod.Get, "http://example.com"),
new HttpRequestMessage(HttpMethod.Post, "http://example.com"),
new HttpRequestMessage(HttpMethod.Put, "http://example.com")
};
ChangeSetRequestItem requestItem = new ChangeSetRequestItem(requests);
Mock<HttpMessageInvoker> invoker = new Mock<HttpMessageInvoker>(new HttpServer());
invoker.Setup(i => i.SendAsync(It.IsAny<HttpRequestMessage>(), CancellationToken.None))
.Returns<HttpRequestMessage, CancellationToken>((req, c) =>
{
if (req.Method == HttpMethod.Post)
{
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest));
}
return Task.FromResult(new HttpResponseMessage());
});
var response = requestItem.SendRequestAsync(invoker.Object, CancellationToken.None).Result;
var changesetResponse = Assert.IsType<ChangeSetResponseItem>(response);
Assert.Equal(1, changesetResponse.Responses.Count());
Assert.Equal(HttpStatusCode.BadRequest, changesetResponse.Responses.First().StatusCode);
}
示例11: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
string identifier = GetUserIdentifier(request);
if (String.IsNullOrEmpty(identifier))
return CreateResponse(request, HttpStatusCode.Forbidden, "Could not identify client.");
string cacheKey = GetCacheKey(identifier);
long requestCount = 0;
using (IRedisClient client = _clientsManager.GetClient()) {
requestCount = client.IncrementValueBy(cacheKey, 1);
if (requestCount == 1)
client.ExpireEntryIn(cacheKey, _period);
}
Task<HttpResponseMessage> response = null;
long maxRequests = _maxRequestsForUserIdentifier(identifier);
if (requestCount > maxRequests)
response = CreateResponse(request, HttpStatusCode.Conflict, _message);
else
response = base.SendAsync(request, cancellationToken);
return response.ContinueWith(task => {
long remaining = maxRequests - requestCount;
if (remaining < 0)
remaining = 0;
HttpResponseMessage httpResponse = task.Result;
httpResponse.Headers.Add("RateLimit-Limit", maxRequests.ToString());
httpResponse.Headers.Add("RateLimit-Remaining", remaining.ToString());
return httpResponse;
});
}
示例12: ByPostShouldReturnCorrectResponse
public void ByPostShouldReturnCorrectResponse()
{
var controller = typeof(CategoriesController);
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
var httpServer = new HttpServer(config);
var httpInvoker = new HttpMessageInvoker(httpServer);
using (httpInvoker)
{
var request = new HttpRequestMessage
{
RequestUri = new Uri("http://test.com/api/categories/1"),
Method = HttpMethod.Get
};
var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;
Assert.IsNotNull(result);
}
}
示例13: Parameter_Constructor
public void Parameter_Constructor()
{
HttpRequestMessage[] requests = new HttpRequestMessage[0];
ChangeSetRequestItem requestItem = new ChangeSetRequestItem(requests);
Assert.Same(requests, requestItem.Requests);
}
示例14: NoRequestContentType_Throws_IfMultipleActionsWithConstraints
public async Task NoRequestContentType_Throws_IfMultipleActionsWithConstraints()
{
// Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"http://localhost/ConsumesAttribute_AmbiguousActions/CreateProduct");
// Act
var response = await client.SendAsync(request);
var exception = response.GetServerException();
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Equal(typeof(AmbiguousActionException).FullName, exception.ExceptionType);
// Mono issue - https://github.com/aspnet/External/issues/19
Assert.Equal(
"Multiple actions matched. The following actions matched route data and had all constraints " +
"satisfied:" + PlatformNormalizer.GetNewLinesAsUnderscores(2) + "ActionConstraintsWebSite." +
"ConsumesAttribute_NoFallBackActionController." +
"CreateProduct" + PlatformNormalizer.GetNewLinesAsUnderscores(1) + "ActionConstraintsWebSite." +
"ConsumesAttribute_NoFallBackActionController.CreateProduct",
exception.ExceptionMessage);
}
示例15: TestRoute
public void TestRoute(string url, string verb, Type type, string actionName)
{
//Arrange
url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
url = Host + url;
//Act
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);
IHttpControllerSelector controller = this.GetControllerSelector();
IHttpActionSelector action = this.GetActionSelector();
IHttpRouteData route = this.Config.Routes.GetRouteData(request);
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;
HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);
HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
{
ControllerDescriptor = controllerDescriptor
};
var actionDescriptor = action.SelectAction(context);
//Assert
Assert.NotNull(controllerDescriptor);
Assert.NotNull(actionDescriptor);
Assert.Equal(type, controllerDescriptor.ControllerType);
Assert.Equal(actionName, actionDescriptor.ActionName);
}