本文整理匯總了C#中System.Net.Http.HttpRequestMessage.GetRequestContext方法的典型用法代碼示例。如果您正苦於以下問題:C# HttpRequestMessage.GetRequestContext方法的具體用法?C# HttpRequestMessage.GetRequestContext怎麽用?C# HttpRequestMessage.GetRequestContext使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Net.Http.HttpRequestMessage
的用法示例。
在下文中一共展示了HttpRequestMessage.GetRequestContext方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: SendAsync
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IPrincipal incomingPrincipal = request.GetRequestContext().Principal;
Debug.WriteLine(string.Format("Principal is authenticated at the start of SendAsync in CustomAuthenticationMessageHandler: {0}", incomingPrincipal.Identity.IsAuthenticated));
if (!incomingPrincipal.Identity.IsAuthenticated)
{
IPrincipal genericPrincipal = new GenericPrincipal(new GenericIdentity("Andras", "CustomIdentification"), new string[] { "Admin", "PowerUser" });
request.GetRequestContext().Principal = genericPrincipal;
}
/*
AuthenticationHeaderValue authHeader = request.Headers.Authorization;
if (authHeader == null || authHeader.Scheme == "Basic")
{
return await SendError("Either no auth header or Basic auth scheme set", HttpStatusCode.Forbidden);
}
HttpRequestHeaders requestHeaders = request.Headers;
IEnumerable<string> authTokenContainer = new List<string>();
bool tryGetCustomAuthHeader = requestHeaders.TryGetValues("x-custom-header", out authTokenContainer);
if (!tryGetCustomAuthHeader)
{
return await SendError("Custom authentication header is missing.", HttpStatusCode.Forbidden);
}*/
return await base.SendAsync(request, cancellationToken);
}
開發者ID:andras-nemes,項目名稱:webapi2securityextensions,代碼行數:25,代碼來源:CustomAuthenticationMessageHandler.cs
示例2: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
var authHeader = request.Headers.Authorization;
string scheme = authHeader != null ? authHeader.Scheme.ToLower() : null;
string token = null;
if (authHeader != null && (scheme == BearerScheme || scheme == TokenScheme)) {
token = authHeader.Parameter;
} else if (authHeader != null && scheme == BasicScheme) {
var authInfo = request.GetBasicAuth();
if (authInfo != null) {
if (authInfo.Username.ToLower() == "client")
token = authInfo.Password;
else if (authInfo.Password.ToLower() == "x-oauth-basic" || String.IsNullOrEmpty(authInfo.Password))
token = authInfo.Username;
else {
User user;
try {
user = _userRepository.GetByEmailAddress(authInfo.Username);
} catch (Exception) {
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
if (user == null || !user.IsActive)
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
if (String.IsNullOrEmpty(user.Salt))
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
string encodedPassword = authInfo.Password.ToSaltedHash(user.Salt);
if (!String.Equals(encodedPassword, user.Password))
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
request.GetRequestContext().Principal = new ClaimsPrincipal(user.ToIdentity());
return await base.SendAsync(request, cancellationToken);
}
}
} else {
string queryToken = request.GetQueryString("access_token");
if (!String.IsNullOrEmpty(queryToken))
token = queryToken;
queryToken = request.GetQueryString("api_key");
if (String.IsNullOrEmpty(token) && !String.IsNullOrEmpty(queryToken))
token = queryToken;
queryToken = request.GetQueryString("apikey");
if (String.IsNullOrEmpty(token) && !String.IsNullOrEmpty(queryToken))
token = queryToken;
}
if (!String.IsNullOrEmpty(token)) {
IPrincipal principal = _tokenManager.Validate(token);
if (principal != null)
request.GetRequestContext().Principal = principal;
}
return await base.SendAsync(request, cancellationToken);
}
示例3: GetBasePath
/// <summary>
/// Returns the base url of the request including virtual directory if any
/// </summary>
/// <param name="request">Request message</param>
/// <returns>Base Url</returns>
public static string GetBasePath(HttpRequestMessage request)
{
string baseUrl = request.RequestUri.Scheme + "://" + request.RequestUri.Host;
if (!string.IsNullOrWhiteSpace(request.GetRequestContext().VirtualPathRoot))
{
baseUrl = baseUrl + request.GetRequestContext().VirtualPathRoot;
}
return baseUrl;
}
示例4: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.GetRequestContext().Principal = new GenericPrincipal(new GenericIdentity("LocalDevUser"), new[] { "User" });
if (HttpContext.Current != null)
{
HttpContext.Current.User = request.GetRequestContext().Principal;
}
return base.SendAsync(request, cancellationToken);
}
示例5: GetUserIdentifier
protected virtual string GetUserIdentifier(HttpRequestMessage request) {
HttpRequestContext ctx = request.GetRequestContext();
if (ctx != null) {
// use organization id or user id as the identifier for throttling
var principal = request.GetRequestContext().Principal as ExceptionlessPrincipal;
if (principal != null)
return principal.Project != null ? principal.Project.OrganizationId : principal.UserEntity.Id;
}
// fallback to using the IP address
var ip = request.GetClientIpAddress();
return Settings.Current.WebsiteMode == WebsiteMode.Dev && String.IsNullOrEmpty(ip) ? "127.0.0.1" : ip;
}
示例6: GetUserIdentifier
protected virtual string GetUserIdentifier(HttpRequestMessage request) {
HttpRequestContext ctx = request.GetRequestContext();
if (ctx != null) {
// use organization id or user id as the identifier for throttling
var principal = request.GetRequestContext().Principal as ExceptionlessPrincipal;
if (principal != null)
return principal.Project != null ? principal.Project.OrganizationId : principal.UserEntity.Id;
}
// fallback to using the IP address
return request.GetClientIpAddress();
}
示例7: SendAsync
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri.Query.ToLower().Contains("includeerror=true"))
{
request.GetRequestContext().IncludeErrorDetail = true;
}
else
{
request.GetRequestContext().IncludeErrorDetail = false;
}
return base.SendAsync(request, cancellationToken);
}
示例8: AddIdentityToCurrentPrincipal
private void AddIdentityToCurrentPrincipal(ClaimsIdentity identity, HttpRequestMessage request)
{
var principal = request.GetRequestContext().Principal as ClaimsPrincipal;
if (principal == null)
{
principal = new ClaimsPrincipal(identity);
request.GetRequestContext().Principal = principal;
}
else
{
principal.AddIdentity(identity);
}
}
示例9: SendAsync
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
HttpResponseMessage res;
if (!request.HasAuthorizationHeaderWithBasicScheme())
{
res = await base.SendAsync(request, cancellationToken);
}
else
{
var principal = await request.TryGetPrincipalFromBasicCredentialsUsing(_validator);
if (principal != null)
{
request.GetRequestContext().Principal = principal;
res = await base.SendAsync(request, cancellationToken);
}
else
{
res = request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
if (res.StatusCode == HttpStatusCode.Unauthorized)
{
res.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", _realm));
}
return res;
}
示例10: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
HttpResponseMessage response;
if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == "Basic")
{
var datosCodificados = request.Headers.Authorization.Parameter.Trim();
var userPass = Encoding.Default.GetString(Convert.FromBase64String(datosCodificados));
var datos = userPass.Split(":".ToCharArray());
var username = datos[0];
var password = datos[1];
GenericPrincipal principal = AuthenticateUser(username, password);
if (principal == null)
{
response = request.CreateResponse(HttpStatusCode.Unauthorized);
response.Headers.Add("WWW-Authenticate", "Basic");
}
else
{
request.GetRequestContext().Principal = principal;
}
}
response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.Add("WWW-Authenticate","Basic");
}
return response;
}
示例11: SendAsync
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var authValue = request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
{
var parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
if (parsedCredentials != null)
request.GetRequestContext().Principal = principalProvider.CreatePrincipal(
parsedCredentials.Username, parsedCredentials.Password);
}
return await base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if(response.StatusCode == HttpStatusCode.Unauthorized &&
!response.Headers.Contains(basicAuthResponseHeader))
response.Headers.Add(basicAuthResponseHeader, basicAuthResponseHeaderValue);
return response;
});
}
示例12: SendAsync
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
var context = request.GetRequestContext();
var user = context.Principal.Identity;
if (!user.IsAuthenticated)
{
IdentityResult result;
ApplicationUserManager userManager = request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var appUser = await userManager.FindByNameAsync(DummyName);
if (appUser == null)
{
appUser = new ApplicationUser() { UserName = DummyName, Email = DummyName };
result = await userManager.CreateAsync(appUser);
}
ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
context.Principal = new ClaimsPrincipal(oAuthIdentity);
}
return await base.SendAsync(request, cancellationToken);
}
示例13: GetHttpActionDescriptorForRestierController
private static HttpActionDescriptor GetHttpActionDescriptorForRestierController(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor)
{
HttpActionDescriptor actionDescriptor;
var perControllerConfig = controllerDescriptor.Configuration;
request.SetConfiguration(perControllerConfig);
var requestContext = request.GetRequestContext();
requestContext.Configuration = perControllerConfig;
requestContext.RouteData = request.GetRouteData();
requestContext.Url = new UrlHelper(request);
requestContext.VirtualPathRoot = perControllerConfig.VirtualPathRoot;
var controller = controllerDescriptor.CreateController(request);
using (controller as IDisposable)
{
var controllerContext = new HttpControllerContext(requestContext, request, controllerDescriptor, controller);
try
{
actionDescriptor = perControllerConfig.Services.GetActionSelector().SelectAction(controllerContext);
}
catch (HttpResponseException ex)
{
if (ex.Response.StatusCode == HttpStatusCode.NotFound || ex.Response.StatusCode == HttpStatusCode.MethodNotAllowed)
{
actionDescriptor = null;
}
else
{
throw;
}
}
}
return actionDescriptor;
}
示例14: Add
public Message Add(HttpRequestMessage request, MessageDto dto)
{
var username = request.GetRequestContext().Principal.Identity.Name;
var profileId = uow.Accounts.GetAll()
.Include(x => x.Profiles).Single(x => x.Email == username)
.Profiles
.First().Id;
Conversation converation = dto.ConversationId == null ? new Conversation() : uow.Conversations.GetById(dto.ConversationId.Value);
var message = new Message()
{
FromProfileId = profileId,
ToProfileId = dto.ToProfileId,
Subject = dto.Subject,
Content = dto.Content,
CreatedDate = DateTime.Now
};
if (dto.ConversationId == null)
{
converation.Messages.Add(message);
uow.Conversations.Add(converation);
}
uow.SaveChanges();
return message;
}
示例15: SendAsync
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool identified = false;
if (request.Headers.Authorization != null && string.Equals(request.Headers.Authorization.Scheme, BasicAuthResponseHeaderValue, StringComparison.CurrentCultureIgnoreCase))
{
var credentials =
Encoding.UTF8.GetString(Convert.FromBase64String(request.Headers.Authorization.Parameter));
var user = credentials.Split(':')[0].Trim();
var pwd = credentials.Split(':')[0].Trim();
//validate username and password here and set identified
if (user == "filip")
{
identified = true;
}
if (identified)
{
var id = new ClaimsIdentity(new[] {new Claim(ClaimTypes.Name, user)}, BasicAuthResponseHeaderValue);
var principal = new ClaimsPrincipal(new[] {id});
request.GetRequestContext().Principal = principal;
}
}
if (!identified)
{
var unauthorizedResponse = request.CreateResponse(HttpStatusCode.Unauthorized);
unauthorizedResponse.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(BasicAuthResponseHeaderValue, Realm));
return Task.FromResult(unauthorizedResponse);
}
return base.SendAsync(request, cancellationToken);
}