本文整理汇总了C#中System.Net.Http.HttpResponseMessage类的典型用法代码示例。如果您正苦于以下问题:C# HttpResponseMessage类的具体用法?C# HttpResponseMessage怎么用?C# HttpResponseMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpResponseMessage类属于System.Net.Http命名空间,在下文中一共展示了HttpResponseMessage类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: 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;
}
开发者ID:rherlt,项目名称:SimpleUniversalWebserver,代码行数:26,代码来源:MainPage.xaml.cs
示例2: ExecuteActionFilterAsync
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
if (actionContext.Request.Headers.Contains("X-AccessToken"))
{
var tokenvalue = actionContext.Request.Headers.GetValues("X-AccessToken").FirstOrDefault();
if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
{
return continuation();
}
}
else if (actionContext.Request.RequestUri.ParseQueryString() != null)
{
var queryValues = actionContext.Request.RequestUri.ParseQueryString();
var tokenvalue = queryValues["token"];
if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
{
return continuation();
}
}
return Task.Factory.StartNew(() =>
{
var retur = new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("This resource cannot be used without the correct access token")
};
return retur;
});
}
开发者ID:unipluss,项目名称:UniAlltid.Language,代码行数:31,代码来源:TokenAccessFilter.cs
示例3: Get
/// <summary>
/// Get the resource description of the api for swagger documentation
/// </summary>
/// <remarks>It is very convenient to have this information available for generating clients. This is the entry point for the swagger UI
/// </remarks>
/// <returns>JSON document representing structure of API</returns>
public HttpResponseMessage Get()
{
var docProvider = (XmlCommentDocumentationProvider)GlobalConfiguration.Configuration.Services.GetDocumentationProvider();
ResourceListing r = SwaggerGen.CreateResourceListing(ControllerContext);
List<string> uniqueControllers = new List<string>();
foreach (var api in GlobalConfiguration.Configuration.Services.GetApiExplorer().ApiDescriptions)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
if (uniqueControllers.Contains(controllerName) ||
controllerName.ToUpper().Equals(SwaggerGen.SWAGGER.ToUpper())) continue;
uniqueControllers.Add(controllerName);
ResourceApi rApi = SwaggerGen.CreateResourceApi(api);
r.apis.Add(rApi);
}
HttpResponseMessage resp = new HttpResponseMessage();
resp.Content = new ObjectContent<ResourceListing>(r, ControllerContext.Configuration.Formatters.JsonFormatter);
return resp;
}
开发者ID:CWISoftware,项目名称:Swagger.Net,代码行数:31,代码来源:SwaggerController.cs
示例4: CanEnrich
public bool CanEnrich(HttpResponseMessage response) {
var content = response.Content as ObjectContent;
return content != null
&& (content.ObjectType == typeof(MediaModel));
}
开发者ID:mahf,项目名称:ASPNETWebAPISamples,代码行数:7,代码来源:MediaResponseEnricher.cs
示例5: AddAndDeleteGridWidgetFromFileSystemVerifyPageToolbox
public void AddAndDeleteGridWidgetFromFileSystemVerifyPageToolbox()
{
RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () => BAT.Macros().NavigateTo().CustomPage("~/sitefinity/pages", false));
RuntimeSettingsModificator.ExecuteWithClientTimeout(800000, () => BAT.Macros().User().EnsureAdminLoggedIn());
BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName);
BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout);
BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton();
BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().DragAndDropLayoutWidgetToPlaceholder(LayoutCaption);
BAT.Wrappers().Backend().Pages().PageLayoutEditorWrapper().VerifyLayoutWidgetPageEditor(LayoutCaption, GridCount1);
BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage();
BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false);
BATFrontend.Wrappers().Frontend().Widgets().GridWidgets().VerifyNewGridWidgetOnTheFrontend(this.layouts);
BAT.Arrange(this.TestName).ExecuteArrangement("DeleteGridWidgetFromFileSystem");
BAT.Macros().NavigateTo().Pages();
BAT.Wrappers().Backend().Pages().PagesWrapper().OpenPageZoneEditor(PageName);
BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().SwitchEditorLayoutMode(EditorLayoutMode.Layout);
BATFrontend.Wrappers().Backend().Widgets().GridWidgets().ClickBootstrapGridWidgetButton();
Assert.IsFalse(
BATFrontend.Wrappers().Backend().Pages().PageZoneEditorWrapper().IsLayoutWidgetPresentInToolbox(LayoutCaption),
"Layout widget is found in the toolbox");
BAT.Wrappers().Backend().Pages().PageZoneEditorWrapper().PublishPage();
BAT.Macros().NavigateTo().CustomPage("~/" + PageName.ToLower(), false);
// Asserts that the page is not throwing an error 500 on the frontend
HttpResponseMessage response = new HttpResponseMessage();
Assert.AreEqual(200, (int)response.StatusCode);
}
开发者ID:sbschase,项目名称:feather,代码行数:31,代码来源:AutoGenerateGridWidgetToToolboxForPage.cs
示例6: ExecuteAsync
public Task<HttpResponseMessage> ExecuteAsync( CancellationToken cancellationToken ) {
//Request.GetOwinContext().Authentication.Challenge( LoginProvider );
HttpResponseMessage response = new HttpResponseMessage( HttpStatusCode.Unauthorized );
response.RequestMessage = Request;
return Task.FromResult( response );
}
开发者ID:jeelliott,项目名称:RestaurantReviews,代码行数:7,代码来源:ChallengeResult.cs
示例7: ThrowIfError
public static void ThrowIfError(HttpResponseMessage response, dynamic json)
{
if (json == null) return;
if (!JsonHelpers.ContainsProperty(json, Constants.ErrorProperty)) return;
var error = json[Constants.ErrorProperty];
if (string.IsNullOrWhiteSpace(error)) return;
CexApiException exception;
if (error == Constants.NonceMustBeIncremented)
{
exception = new CexNonceException(response, Constants.NonceMustBeIncremented);
}
else if (error == Constants.PermissionDenied)
{
exception = new CexPermissionDeniedException(response, Constants.PermissionDenied);
}
else if (error == Constants.InvalidApiKey)
{
exception = new CexInvalidApiKeyException(response, Constants.InvalidApiKey);
}
else
{
exception = new CexApiException(response, error);
}
throw exception;
}
开发者ID:jordansjones,项目名称:Cex.io-Api-Client,代码行数:30,代码来源:ExceptionOracle.cs
示例8: CreateSuccessTokenResponseMessage
public static HttpResponseMessage CreateSuccessTokenResponseMessage()
{
HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.OK);
HttpContent content = new StringContent("{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"scope\":\"some-scope1 some-scope2\",\"access_token\":\"some-access-token\",\"refresh_token\":\"OAAsomethingencryptedQwgAA\",\"id_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9.eyJhdWQiOiJlODU0YTRhNy02YzM0LTQ0OWMtYjIzNy1mYzdhMjgwOTNkODQiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNmMzZDUxZGQtZjBlNS00OTU5LWI0ZWEtYTgwYzRlMzZmZTVlL3YyLjAvIiwiaWF0IjoxNDU1ODMzODI4LCJuYmYiOjE0NTU4MzM4MjgsImV4cCI6MTQ1NTgzNzcyOCwiaXBhZGRyIjoiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6Ik1hcmlvIFJvc3NpIiwib2lkIjoidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjoiZGlzcGxheWFibGVAaWQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSIsInZlciI6IjIuMCJ9.Z6Xc_PzqTtB-2TjyZwPpFGgkAs47m95F_I-NHxtIJT-H20i_1kbcBdmJaj7lMjHhJwAAMM-tE-iBVF9f7jNmsDZAADt-HgtrrXaXxkIKMwQ_MuB-OI4uY9KYIurEqmkGvOlRUK1ZVNNf7IKE5pqNTOZzyFDEyG8SwSvAmN-J4VnrxFz3d47klHoKVKwLjWJDj7edR2UUkdUQ6ZRj7YBj9UjC8UrmVNLBmvyatPyu9KQxyNyJpmTBT2jDjMZ3J1Z5iL98zWw_Ez0-6W0ti87UaPreJO3hejqQE_pRa4rXMLpw3oAnyEE1H7n0F6tK_3lJndZi9uLTIsdSMEXVnZdoHg\",\"id_token_expires_in\":\"3600\",\"profile_info\":\"eyJ2ZXIiOiIxLjAiLCJuYW1lIjoiTWFyaW8gUm9zc2kiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJtYXJpb0BkZXZlbG9wZXJ0ZW5hbnQub25taWNyb3NvZnQuY29tIiwic3ViIjoiSzRfU0dHeEtxVzFTeFVBbWhnNkMxRjZWUGlGemN4LVFkODBlaElFZEZ1cyIsInRpZCI6IjZjM2Q1MWRkLWYwZTUtNDk1OS1iNGVhLWE4MGM0ZTM2ZmU1ZSJ9\"}");
responseMessage.Content = content;
return responseMessage;
}
开发者ID:AzureAD,项目名称:microsoft-authentication-library-for-dotnet,代码行数:7,代码来源:MockHelpers.cs
示例9: HandleResponseAsync
public override Task<HttpResponseMessage> HandleResponseAsync(string linkRelation, HttpResponseMessage responseMessage)
{
_action(linkRelation, responseMessage);
return base.HandleResponseAsync(linkRelation, responseMessage);
}
开发者ID:hapikit,项目名称:hapikit.net,代码行数:7,代码来源:InlineResponseHandler.cs
示例10: RetryAfter_RetryHeader_100
public void RetryAfter_RetryHeader_100()
{
var headers = new HttpResponseMessage().Headers;
headers.Add("Retry-After", "100");
var response = new FitbitResponse<string>((HttpStatusCode)429, headers, null);
Assert.AreEqual(100, response.RetryAfter());
}
开发者ID:lobrien,项目名称:Fitbit.NET,代码行数:7,代码来源:FitbitResponseTests.cs
示例11: WebApiResponseMessage
public WebApiResponseMessage(HttpResponseMessage response) : base(response.Content)
{
this.response = response;
this.response.Headers.ToList()
.ForEach(h => this.messageHeaders.Add(h.Key, h.Value.ToArray()));
}
开发者ID:RyanLiu99,项目名称:Thinktecture.IdentityModel,代码行数:7,代码来源:WebApiResponseMessage.cs
示例12: Execute
private HttpResponseMessage Execute()
{
HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
response.RequestMessage = request;
response.ReasonPhrase = errorMessage;
return response;
}
开发者ID:vinhxuando,项目名称:TicketBooking,代码行数:7,代码来源:AuthenticationFailureResult.cs
示例13: ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws
public void ExecuteExceptionFilterAsync_Throws_And_Traces_When_Inner_OnException_Throws()
{
// Arrange
HttpRequestMessage request = new HttpRequestMessage();
HttpResponseMessage response = new HttpResponseMessage();
Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
InvalidOperationException exception = new InvalidOperationException("test");
mockAttr.Setup(a => a.OnException(It.IsAny<HttpActionExecutedContext>())).Throws(exception);
Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
TestTraceWriter traceWriter = new TestTraceWriter();
ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
TraceRecord[] expectedTraces = new TraceRecord[]
{
new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Error) { Kind = TraceKind.End, Operation = "OnException" }
};
// Act
Exception thrown =
Assert.Throws<InvalidOperationException>(
() => ((IExceptionFilter) tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None));
// Assert
Assert.Same(exception, thrown);
Assert.Same(exception, traceWriter.Traces[1].Exception);
Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
}
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:30,代码来源:ExceptionFilterAttributeTracerTest.cs
示例14: ExecuteExceptionFilterAsync_Traces
public void ExecuteExceptionFilterAsync_Traces()
{
// Arrange
HttpRequestMessage request = new HttpRequestMessage();
HttpResponseMessage response = new HttpResponseMessage();
Mock<ExceptionFilterAttribute> mockAttr = new Mock<ExceptionFilterAttribute>() { CallBase = true };
Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection<HttpParameterDescriptor>(new HttpParameterDescriptor[0]));
HttpActionExecutedContext actionExecutedContext = ContextUtil.GetActionExecutedContext(request, response);
TestTraceWriter traceWriter = new TestTraceWriter();
ExceptionFilterAttributeTracer tracer = new ExceptionFilterAttributeTracer(mockAttr.Object, traceWriter);
TraceRecord[] expectedTraces = new TraceRecord[]
{
new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.Begin, Operation = "OnException" },
new TraceRecord(request, TraceCategories.FiltersCategory, TraceLevel.Info) { Kind = TraceKind.End, Operation = "OnException" },
};
// Act
Task task = ((IExceptionFilter)tracer).ExecuteExceptionFilterAsync(actionExecutedContext, CancellationToken.None);
task.Wait();
// Assert
Assert.Equal<TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
}
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:25,代码来源:ExceptionFilterAttributeTracerTest.cs
示例15: PostTest
public void PostTest()
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
var result = _contactController.Post(contact);
Assert.AreEqual(response.StatusCode, result.StatusCode);
}
开发者ID:zannik,项目名称:APIRestTest,代码行数:7,代码来源:UnitTest1.cs
示例16: GetProvidersData
public HttpResponseMessage GetProvidersData([FromUri]Filter filter)
{
string factualJsonData;
try
{
factualJsonData = repository.GetHealthCareProviderData(filter);
}
catch (FactualApiException ex)
{
throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message) });
}
// Get the IContentNegotiator
IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
// Run content negotiation to select a formatter
ContentNegotiationResult result = negotiator.Negotiate(
typeof(string), this.Request, this.Configuration.Formatters);
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (result.MediaType.MediaType.Equals("application/xml"))
{
string json = string.Format("{0}{1}{2}", "{Root: ", factualJsonData, "}");
var doc = (XDocument)JsonConvert.DeserializeXNode(json);
response.Content = new StringContent(doc.ToString(), Encoding.UTF8, result.MediaType.MediaType);
}
else
response.Content = new StringContent(factualJsonData, Encoding.UTF8, "application/json");
return response;
}
开发者ID:ranjancse26,项目名称:HealthCareProvider,代码行数:33,代码来源:HealthCareProviderController.cs
示例17: OnException
public override void OnException(HttpActionExecutedContext context)
{
Exception exp;
try
{
var logLevel = GetLogLevel(context.Exception);
_logException(context.Exception, logLevel);
var error = ToError(context.Exception);
var httpResponseMessage = new HttpResponseMessage
{
StatusCode = GetStatusCode(context.Exception),
ReasonPhrase = context.Exception.Message,
RequestMessage = context.Request,
Content = new ObjectContent<Error>(error, new JsonMediaTypeFormatter(), "application/json"),
};
exp = new HttpResponseException(httpResponseMessage);
}
catch (Exception exception)
{
var e = new AggregateException(exception, context.Exception);
_logException(e, LogLevel.SystemError);
throw;
}
throw exp;
}
开发者ID:Quilt4,项目名称:Quilt4.Service,代码行数:27,代码来源:ExceptionHandlingAttribute.cs
示例18: OnAuthorization
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
bool authorized = false;
var controller = actionContext.ControllerContext.Controller as ApiAuthorizeController;
if (controller != null)
{
var cookie = actionContext.Request.Headers.GetCookies().Select(
c => c[controller.Authenticator.CookieTicketConfig.CookieName]).FirstOrDefault();
CookieHeaderValue cookieValue;
CookieTicket ticket;
if (controller.Authenticator.ValidateCookieTicket(cookie, out ticket, out cookieValue))
{
authorized = true;
controller.UserId = int.Parse(ticket.Name);
if (cookieValue != null)
{
actionContext.Request.Properties.Add(RenewAuthorizationCookieToken, cookieValue);
}
}
}
if (!authorized)
{
var message = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
actionContext.Response = message;
}
}
开发者ID:coolworker,项目名称:yue,代码行数:27,代码来源:ApiAuthorizeAttribute.cs
示例19: CreateInvalidGrantTokenResponseMessage
public static HttpResponseMessage CreateInvalidGrantTokenResponseMessage()
{
HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
HttpContent content = new StringContent("{\"error\":\"invalid_grant\",\"error_description\":\"AADSTS70002: Error validating credentials.AADSTS70008: The provided access grant is expired or revoked.Trace ID: f7ec686c-9196-4220-a754-cd9197de44e9Correlation ID: 04bb0cae-580b-49ac-9a10-b6c3316b1eaaTimestamp: 2015-09-16 07:24:55Z\",\"error_codes\":[70002,70008],\"timestamp\":\"2015-09-16 07:24:55Z\",\"trace_id\":\"f7ec686c-9196-4220-a754-cd9197de44e9\",\"correlation_id\":\"04bb0cae-580b-49ac-9a10-b6c3316b1eaa\"}");
responseMessage.Content = content;
return responseMessage;
}
开发者ID:AzureAD,项目名称:microsoft-authentication-library-for-dotnet,代码行数:7,代码来源:MockHelpers.cs
示例20: TestDeleteAzureMediaServiceAccountAsync404
public void TestDeleteAzureMediaServiceAccountAsync404()
{
FakeHttpMessageHandler fakeHttpHandler;
MediaServicesManagementClient clientWithHandler = CreateMediaManagementClientWithFakeHttpMessageHandler(out fakeHttpHandler);
const string responseText = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">{\"Code\":\"NotFound\",\"Message\":\"The specified account was not found.\"}</string>";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new FakeHttpContent(responseText)
};
fakeHttpHandler.Send = request => response;
MediaServicesClient target = new MediaServicesClient(null,
clientWithHandler,
StorageClient.WithHandler(new FakeHttpMessageHandler()));
try
{
OperationResponse result = target.DeleteAzureMediaServiceAccountAsync(AccountName).Result;
}
catch (AggregateException ax)
{
CloudException x = (CloudException)ax.InnerExceptions.Single();
Assert.AreEqual(HttpStatusCode.NotFound, x.Response.StatusCode);
return;
}
Assert.Fail("ServiceManagementClientException expected");
}
开发者ID:EmmaZhu,项目名称:azure-sdk-tools,代码行数:31,代码来源:MediaServicesClientTests.cs
注:本文中的System.Net.Http.HttpResponseMessage类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论