本文整理匯總了C#中System.Net.Http.HttpRequestMessage.GetDependencyScope方法的典型用法代碼示例。如果您正苦於以下問題:C# HttpRequestMessage.GetDependencyScope方法的具體用法?C# HttpRequestMessage.GetDependencyScope怎麽用?C# HttpRequestMessage.GetDependencyScope使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.GetDependencyScope方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: SendAsync
/// <summary>
/// Web API custom message handler that verifies whether or not a pool exists in the persistence store that has a pool id included in a request URI. If a pool with the id does not exist, an HTTP status code of "Not Found" is returned.
/// </summary>
/// <param name="request">HTTP request message.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>Task representing an asynchronous invocation of the message being sent.</returns>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", "request cannot be null.");
}
if (cancellationToken == null)
{
throw new ArgumentNullException("cancellationToken", "cancellationToken cannot be null.");
}
////Verify that pool exists in persistence store.
////TODO: When creating route constraint, be sure to constrain value to int.
int poolId = Convert.ToInt32(request.GetRouteData().Values["poolId"]);
IPoolRepository poolRepository = (IPoolRepository)request.GetDependencyScope().GetService(typeof(IPoolRepository));
////Retrieve pool entity from persistence store.
Pool poolToCheckExists = poolRepository.GetById(poolId);
////If pool does not exist in persistence store, return HTTP status code of "Not Found"
////NOTE: This return value is left intentionally vague so a potential hacker does not know what is missing from the URI.
if (poolToCheckExists == null)
{
Task.FromResult(request.CreateResponse(HttpStatusCode.NotFound));
}
return base.SendAsync(request, cancellationToken);
}
示例2: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (_lockManager == null)
{
//http://www.strathweb.com/2012/11/asp-net-web-api-and-dependencies-in-request-scope/
_lockManager = request.GetDependencyScope().GetService(typeof(ILockManager)) as ILockManager;
}
// Preconditions
HttpResponseMessage error;
if (!TryNoLockTokenMatchesRequestUri(request, out error))
{
return base.SendAsync(request, cancellationToken)
.ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
}
if (!TryNoLockTokenSubmitted(request, out error))
{
return base.SendAsync(request, cancellationToken)
.ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
}
if (!TryNoConflictingLock(request, out error))
{
return base.SendAsync(request, cancellationToken)
.ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
}
return base.SendAsync(request, cancellationToken);
}
示例3: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var scope = request.GetDependencyScope();
var currentRequest = (CurrentRequest)scope.GetService(typeof(CurrentRequest));
currentRequest.Value = request;
return base.SendAsync(request, cancellationToken);
}
示例4: SendAsync
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
IHttpRouteData routeData = request.GetRouteData();
int key;
if(!int.TryParse(routeData.Values["customerkey"].ToString(), out key)) {
return Task.FromResult(
request.CreateResponse(HttpStatusCode.NotFound)
);
}
var dependecyScope = request.GetDependencyScope();
var customerRepo = (IEntityRepository<Customer>)dependecyScope.GetService(typeof(IEntityRepository<Customer>));
var customer = customerRepo.GetSingle(key);
if (customer == null) {
return Task.FromResult(
request.CreateResponse(HttpStatusCode.NotFound)
);
}
return base.SendAsync(request, cancellationToken);
}
示例5: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (accountService == null)
accountService = request.GetDependencyScope().GetService(typeof (IAccountService)) as IAccountService;
var headers = request.Headers;
if(headers.Authorization == null || headers.Authorization.Scheme != Scheme)
return base.SendAsync(request, cancellationToken);
var values = Encoding.ASCII.GetString(Convert.FromBase64String(headers.Authorization.Parameter)).Split(':');
string userName = values[0].Trim();
string password = values[1].Trim();
//var account = accountService.Get(userName, password);
//if (account == null)
// return base.SendAsync(request, cancellationToken);
//var principal = new GenericPrincipal(new GenericIdentity(userName),
// new[] {((RoleType) account.RoleType).ToString()});
var principal = new GenericPrincipal(new GenericIdentity(userName),
new[] {"Admin"});
Thread.CurrentPrincipal = principal;
request.Properties.Add("user", principal);
return base.SendAsync(request, cancellationToken);
}
示例6: Create
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
var scope = request.GetDependencyScope();
return scope.GetService(controllerType) as IHttpController;
}
示例7: Create
/// <summary>
/// Creates the <see cref="IHttpController"/> specified by <paramref name="controllerType"/> using the given <paramref name="request"/>
/// </summary>
/// <param name="request">The request message.</param>
/// <param name="controllerType">Type of the controller.</param>
/// <param name="controllerDescriptor">The controller descriptor</param>
/// <returns>An instance of type <paramref name="controllerType"/>.</returns>
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
if (controllerDescriptor == null)
{
throw Error.ArgumentNull("controllerDescriptor");
}
if (controllerType == null)
{
throw Error.ArgumentNull("controllerType");
}
try
{
// First check in the local fast cache and if not a match then look in the broader
// HttpControllerDescriptor.Properties cache
if (_fastCache == null)
{
// If dependency resolver returns controller object then keep asking it whenever we need a new instance
IHttpController instance = (IHttpController)request.GetDependencyScope().GetService(controllerType);
if (instance != null)
{
return instance;
}
// Otherwise create a delegate for creating a new instance of the type
Func<IHttpController> activator = TypeActivator.Create<IHttpController>(controllerType);
Tuple<HttpControllerDescriptor, Func<IHttpController>> cacheItem = Tuple.Create(controllerDescriptor, activator);
Interlocked.CompareExchange(ref _fastCache, cacheItem, null);
// Execute the delegate
return activator();
}
else if (_fastCache.Item1 == controllerDescriptor)
{
// If the key matches and we already have the delegate for creating an instance then just execute it
return _fastCache.Item2();
}
else
{
// If the key doesn't match then lookup/create delegate in the HttpControllerDescriptor.Properties for
// that HttpControllerDescriptor instance
Func<IHttpController> activator = (Func<IHttpController>)controllerDescriptor.Properties.GetOrAdd(
_cacheKey,
key => TypeActivator.Create<IHttpController>(controllerType));
return activator();
}
}
catch (Exception ex)
{
throw Error.InvalidOperation(ex, SRResources.DefaultControllerFactory_ErrorCreatingController, controllerType.Name);
}
}
示例8: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var contextManager = request.GetDependencyScope().GetService(typeof(IContextManager)) as IContextManager;
if (contextManager != null)
request.RegisterForDispose(contextManager);
return base.SendAsync(request, cancellationToken);
}
示例9: EnsureCache
protected virtual void EnsureCache(HttpConfiguration config, HttpRequestMessage req)
{
object cache;
config.Properties.TryGetValue(typeof (IApiOutputCache), out cache);
var cacheFunc = cache as Func<IApiOutputCache>;
_webApiCache = cacheFunc != null ? cacheFunc() : req.GetDependencyScope().GetService(typeof(IApiOutputCache)) as IApiOutputCache ?? new MemoryCacheDefault();
}
示例10: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Message handler is created on application start, not per request, so we need to resolve the authentication service using the dependencyscope (this is in request scope)
_authenticationService = request.GetDependencyScope().GetService(typeof(IAuthenticationService)) as IAuthenticationService;
if (_authenticationService == null)
{
throw new ApplicationException("Authentication service cannot be resolved");
}
// Try get authentication header
var authorisationHeader = request.Headers.Authorization;
// If authentication header is available and is set to basic authentication
if (authorisationHeader != null && Scheme.Equals(authorisationHeader.Scheme))
{
string username;
string password;
try
{
username = authorisationHeader.Username();
password = authorisationHeader.Password();
}
catch
{
// If authorization header cannot be properly read, give back sensible error
return request.CreateResponse(HttpStatusCode.BadRequest, "Authorization header is not properly formatted.");
}
// Authenticate request
var authenticateResponse = _authenticationService.IsAuthenticated(username, password);
// Set user if authentication is successfull
if (authenticateResponse)
{
var claimsIdentity = new ClaimsIdentity(AuthenticationTypes.Password);
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, username));
// Do not use thread.principal or httpcontext to set user. This will create dependency on system.web, which stands in the way of self hosting
// http://brockallen.com/2013/10/27/host-authentication-and-web-api-with-owin-and-active-vs-passive-authentication-middleware/
request.GetRequestContext().Principal = new ClaimsPrincipal(claimsIdentity);
}
}
// Process request
var response = await base.SendAsync(request, cancellationToken);
// Add header to indicate basic authentication is needed when request is unauthorized
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(Scheme));
response.Content = new JsonContent(new { Error = "Unauthorized" });
}
return response;
}
示例11: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var existingScope = request.GetDependencyScope();
var dependencyScope = request.GetSuperscribeDependencyScope(existingScope);
request.Properties[HttpPropertyKeys.DependencyScope] = dependencyScope;
request.RegisterForDispose(dependencyScope);
return base.SendAsync(request, cancellationToken);
}
示例12: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var loggingService = LoggingService ?? request.GetDependencyScope().GetService(typeof (ILoggingService)) as ILoggingService;
if (loggingService != null)
{
loggingService.Log(request.RequestUri.ToString());
}
return base.SendAsync(request, cancellationToken);
}
示例13: UpdateScopeWithHttpRequestMessage
/// <summary>
/// Updates the current dependency scope with current HTTP request message.
/// </summary>
/// <param name="request">The HTTP request message.</param>
internal static void UpdateScopeWithHttpRequestMessage(HttpRequestMessage request)
{
var scope = request.GetDependencyScope();
var requestScope = scope.GetRequestLifetimeScope();
if (requestScope == null) return;
var registry = requestScope.ComponentRegistry;
var builder = new ContainerBuilder();
builder.Register(c => request).InstancePerApiRequest();
builder.Update(registry);
}
示例14: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var scope = request.GetDependencyScope();
var service = scope.GetService(typeof (IService)) as IService;
if (service != null)
{
Debug.WriteLine(service.SaySomething("Something from a handler"));
}
return base.SendAsync(request, cancellationToken);
}
示例15: GetUnitOfWork
private static IUnitOfWork GetUnitOfWork(HttpRequestMessage request)
{
var unitOfWork = request.GetDependencyScope().GetService(typeof (IUnitOfWork)) as IUnitOfWork;
if (unitOfWork == null)
{
throw new InvalidOperationException("UOW is missing");
}
return unitOfWork;
}