本文整理匯總了C#中System.Net.Http.HttpRequestMessage.GetConfiguration方法的典型用法代碼示例。如果您正苦於以下問題:C# HttpRequestMessage.GetConfiguration方法的具體用法?C# HttpRequestMessage.GetConfiguration怎麽用?C# HttpRequestMessage.GetConfiguration使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.GetConfiguration方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//得到描述目標Action的HttpActionDescriptor
HttpMethod originalMethod = request.Method;
bool isPreflightRequest = request.IsPreflightRequest();
if (isPreflightRequest)
{
string method = request.Headers.GetValues("Access-Control-Request-Method").First();
request.Method = new HttpMethod(method);
}
HttpConfiguration configuration = request.GetConfiguration();
HttpControllerDescriptor controllerDescriptor = configuration.Services.GetHttpControllerSelector().SelectController(request);
HttpControllerContext controllerContext = new HttpControllerContext(request.GetConfiguration(), request.GetRouteData(), request)
{
ControllerDescriptor = controllerDescriptor
};
HttpActionDescriptor actionDescriptor = configuration.Services.GetActionSelector().SelectAction(controllerContext);
//根據HttpActionDescriptor得到應用的CorsAttribute特性
CorsAttribute corsAttribute = actionDescriptor.GetCustomAttributes<CorsAttribute>().FirstOrDefault() ??
controllerDescriptor.GetCustomAttributes<CorsAttribute>().FirstOrDefault();
if (null == corsAttribute)
{
return base.SendAsync(request, cancellationToken);
}
//利用CorsAttribute實施授權並生成響應報頭
IDictionary<string, string> headers;
request.Method = originalMethod;
bool authorized = corsAttribute.TryEvaluate(request, out headers);
HttpResponseMessage response;
if (isPreflightRequest)
{
if (authorized)
{
response = new HttpResponseMessage(HttpStatusCode.OK);
}
else
{
response = request.CreateErrorResponse(HttpStatusCode.BadRequest, corsAttribute.ErrorMessage);
}
}
else
{
response = base.SendAsync(request, cancellationToken).Result;
}
//添加響應報頭
if (headers != null && headers.Any())
foreach (var item in headers)
response.Headers.Add(item.Key, item.Value);
return Task.Factory.StartNew(() => response);
//only .net4.5 supports Task.FromResult
//return Task.FromResult<HttpResponseMessage>(response);
}
示例2: GetPerRequestFormatterInstance
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
if (_viewLocator == null || _viewParser == null)
{
var config = request.GetConfiguration();
if (config != null)
{
IViewLocator viewLocator = null;
IViewParser viewParser = null;
var resolver = config.DependencyResolver;
if (_viewLocator == null)
viewLocator = (IViewLocator) resolver.GetService(typeof (IViewLocator));
if (_viewParser == null)
viewParser = (IViewParser) resolver.GetService(typeof (IViewParser));
return new HtmlMediaTypeViewFormatter(_siteRootPath, viewLocator, viewParser);
}
}
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
示例3: ContentFor
private HttpContent ContentFor(HttpRequestMessage request, SwaggerDocument swaggerDoc)
{
var negotiator = request.GetConfiguration().Services.GetContentNegotiator();
var result = negotiator.Negotiate(typeof(SwaggerDocument), request, GetSupportedSwaggerFormatters());
return new ObjectContent(typeof(SwaggerDocument), swaggerDoc, result.Formatter, result.MediaType);
}
示例4: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Collection<IResponseEnricher> enrichers = request.GetConfiguration().GetResponseEnrichers();
return enrichers.Where(e => e.CanEnrich(response))
.Aggregate(response, (resp, enricher) => enricher.Enrich(response));
}
示例5: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpConfiguration config = request.GetConfiguration();
IHostPrincipalService principalService = config.Services.GetHostPrincipalService();
IPrincipal principal = principalService.GetCurrentPrincipal(request);
if (!principal.Identity.IsAuthenticated || !SuppressIfAlreadyAuthenticated)
{
if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == _httpBasicSchemeName)
{
string username, password;
if (TryExtractBasicAuthCredentialsFromHeader(request.Headers.Authorization.Parameter, out username, out password))
{
IPrincipal returnedPrincipal = await AuthenticateUserAsync(request, username, password, cancellationToken);
// Check if the user has been authenticated successfully
if (returnedPrincipal != null)
{
principalService.SetCurrentPrincipal(returnedPrincipal, request);
return await base.SendAsync(request, cancellationToken);
}
}
}
}
// Request is not authanticated. Handle unauthenticated request.
return await HandleUnauthenticatedRequestImpl(request, cancellationToken);
}
示例6: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Options)
{
var apiExplorer = request.GetConfiguration().Services.GetApiExplorer();
var controllerRequested = request.GetRouteData().Values["controller"] as string;
var supportedMethods = apiExplorer.ApiDescriptions
.Where(d =>
{
var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName;
return string.Equals(
controller, controllerRequested, StringComparison.OrdinalIgnoreCase);
})
.Select(d => d.HttpMethod.Method)
.Distinct();
if (!supportedMethods.Any())
{
return Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods));
return Task.FromResult(response);
}
return base.SendAsync(request, cancellationToken);
}
示例7: ProcessBatchAsync
/// <inheritdoc/>
public override async Task<HttpResponseMessage> ProcessBatchAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
ValidateRequest(request);
IList<ODataBatchRequestItem> subRequests = await ParseBatchRequestsAsync(request, cancellationToken);
string preferHeader = RequestPreferenceHelpers.GetRequestPreferHeader(request);
if ((preferHeader != null && preferHeader.Contains(PreferenceContinueOnError)) || (!request.GetConfiguration().HasEnabledContinueOnErrorHeader()))
{
ContinueOnError = true;
}
else
{
ContinueOnError = false;
}
try
{
IList<ODataBatchResponseItem> responses = await ExecuteRequestMessagesAsync(subRequests, cancellationToken);
return await CreateResponseMessageAsync(responses, request, cancellationToken);
}
finally
{
foreach (ODataBatchRequestItem subRequest in subRequests)
{
request.RegisterForDispose(subRequest.GetResourcesForDisposal());
request.RegisterForDispose(subRequest);
}
}
}
示例8: GetCorsPolicyProvider
public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
CorsRequestContext corsRequestContext = request.GetCorsRequestContext();
HttpActionDescriptor actionDescriptor = null;
if (corsRequestContext.IsPreflight)
{
HttpRequestMessage targetRequest = new HttpRequestMessage(new HttpMethod(corsRequestContext.AccessControlRequestMethod), request.RequestUri);
request.RegisterForDispose(targetRequest);
try
{
foreach (var property in request.Properties)
{
// The RouteData and HttpContext from the preflight request properties contain information
// relevant to the preflight request and not the actual request, therefore we need to exclude them.
if (property.Key != HttpPropertyKeys.HttpRouteDataKey &&
property.Key != HttpContextBaseKey)
{
targetRequest.Properties.Add(property.Key, property.Value);
}
}
HttpConfiguration config = request.GetConfiguration();
if (config == null)
{
throw new InvalidOperationException(SRResources.NoConfiguration);
}
IHttpRouteData routeData = config.Routes.GetRouteData(request);
if (routeData == null)
{
// No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned
// and let the CorsMessageHandler flow the request to the normal Web API pipeline.
return null;
}
actionDescriptor = SelectAction(targetRequest, routeData, config);
}
catch
{
if (DefaultPolicyProvider != null)
{
return DefaultPolicyProvider;
}
throw;
}
}
else
{
actionDescriptor = request.GetActionDescriptor();
}
return GetCorsPolicyProvider(actionDescriptor);
}
示例9: DefaultRootUrlResolver
/// <summary>
///
/// </summary>
/// <returns></returns>
internal static string DefaultRootUrlResolver(HttpRequestMessage request)
{
string text = request.GetConfiguration().VirtualPathRoot.TrimEnd(new char[] { '/' });
Uri requestUri = request.RequestUri;
return string.Format(CultureInfo.InvariantCulture, "{0}://{1}:{2}{3}", new object[]
{
requestUri.Scheme, requestUri.Host, requestUri.Port, text
});
}
示例10: SelectController
public HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
// Uses the current State key to create the Web Api Controller Type
return new HttpControllerDescriptor
{
Configuration = request.GetConfiguration(),
ControllerType = Type.GetType("NavigationEdgeApi.Controllers." + request.Properties["key"] + "Controller", true, true)
};
}
示例11: HandleOptionsRequestAsync
private async Task<HttpResponseMessage> HandleOptionsRequestAsync(HttpRequestMessage request)
{
var apis = GetMatchingApis(request.GetConfiguration().Routes, request).ToList();
if (!apis.Any())
return await Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
var supportedMethods = apis.Select(i => i.Method)
.Distinct()
.ToList();
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Headers.Add("Access-Control-Allow-Methods", string.Join(",", supportedMethods));
var neg = request.GetConfiguration().Services.GetContentNegotiator();
var res = neg.Negotiate(typeof (IEnumerable<SimpleApiDescription>), request, request.GetConfiguration().Formatters);
resp.Content = new ObjectContent(typeof(IEnumerable<SimpleApiDescription>), apis, res.Formatter);
return await Task.FromResult(resp);
}
示例12: DefaultRootUrlResolver
public static string DefaultRootUrlResolver(HttpRequestMessage request)
{
var scheme = GetHeaderValue(request, "X-Forwarded-Proto") ?? request.RequestUri.Scheme;
var host = GetHeaderValue(request, "X-Forwarded-Host") ?? request.RequestUri.Host;
var port = GetHeaderValue(request, "X-Forwarded-Port") ?? request.RequestUri.Port.ToString(CultureInfo.InvariantCulture);
var httpConfiguration = request.GetConfiguration();
var virtualPathRoot = httpConfiguration.VirtualPathRoot.TrimEnd('/');
return string.Format("{0}://{1}:{2}{3}", scheme, host, port, virtualPathRoot);
}
示例13: SendAsync
/// <inheritdoc/>
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
HttpConfiguration configuration = request.GetConfiguration();
if (configuration == null)
{
throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration);
}
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
// Do not interfere with null responses, we want to buble it up to the top.
// Do not handle 204 responses as the spec says a 204 response must not include an ETag header
// unless the request's representation data was saved without any transformation applied to the body
// (i.e., the resource's new representation data is identical to the representation data received in the
// PUT request) and the ETag value reflects the new representation.
// Even in that case returning an ETag is optional and it requires access to the original object which is
// not possible with the current architecture, so if the user is interested he can set the ETag in that
// case by himself on the response.
if (response == null || !response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.NoContent)
{
return response;
}
ODataPath path = request.ODataProperties().Path;
IEdmModel model = request.ODataProperties().Model;
IEdmEntityType edmType = GetSingleEntityEntityType(path);
object value = GetSingleEntityObject(response);
IEdmEntityTypeReference typeReference = GetTypeReference(model, edmType, value);
if (typeReference != null)
{
EntityInstanceContext context = CreateInstanceContext(typeReference, value);
context.EdmModel = model;
context.NavigationSource = path.NavigationSource;
IETagHandler etagHandler = configuration.GetETagHandler();
EntityTagHeaderValue etag = CreateETag(context, etagHandler);
if (etag != null)
{
response.Headers.ETag = etag;
}
}
return response;
}
示例14: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
var enrichers = request.GetConfiguration().GetResponseEnrichers();
return enrichers.Where(e => e.CanEnrich(response))
.Aggregate(response, (resp, enricher) => enricher.Enrich(response));
});
}
示例15: ConfigureFormatter
/// <summary>
/// Configure the JsonFormatter to only serialize the requested properties
/// </summary>
/// <param name="request"></param>
/// <param name="includedTypeProperties"></param>
private void ConfigureFormatter(HttpRequestMessage request, Dictionary<Type, List<string>> includedTypeProperties)
{
var jsonFormatter = request.GetConfiguration().Formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
//settings.Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
//{
// logger.Error(args.ErrorContext.Error.Message);
// args.ErrorContext.Handled = true;
//};
settings.ContractResolver = new NHIncludingContractResolver(NHEagerFetch.sessionFactory, includedTypeProperties);
}