当前位置: 首页>>代码示例>>C#>>正文


C# HttpRequestMessage.GetRequestContext方法代码示例

本文整理汇总了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);
        }
开发者ID:aamarber,项目名称:Exceptionless,代码行数:58,代码来源:AuthMessageHandler.cs

示例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;
 }
开发者ID:szwork2013,项目名称:BoiPlt,代码行数:14,代码来源:SwaggerConfig.cs

示例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);
        }
开发者ID:bfallar3,项目名称:DDD-rebar-demo,代码行数:10,代码来源:EmptyAuthenticationHandler.cs

示例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;
 }
开发者ID:priestd09,项目名称:Exceptionless,代码行数:12,代码来源:ThrottlingHandler.cs

示例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();
        }
开发者ID:khoussem,项目名称:Exceptionless,代码行数:12,代码来源:ThrottlingHandler.cs

示例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);
 }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:13,代码来源:PolicySetterHandler.cs

示例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);
     }
 }
开发者ID:wukaixian,项目名称:WebApiBook.Security,代码行数:13,代码来源:X509CertificateMessageHandler.cs

示例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;
        }
开发者ID:joergjo,项目名称:WebApiBook.Security,代码行数:28,代码来源:BasicAuthenticationDelegatingHandler.cs

示例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;
        }
开发者ID:M1r3l,项目名称:Lab4Api,代码行数:31,代码来源:AuthMessageHandler.cs

示例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;

                });
        }
开发者ID:cesaroll,项目名称:RESTful_Services_WebAPI,代码行数:27,代码来源:BasicAuthenticationHandler.cs

示例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);
        }
开发者ID:smithyhammer,项目名称:Altostratus,代码行数:25,代码来源:DummyUserHandler.cs

示例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;
        }
开发者ID:bigred8982,项目名称:Swashbuckle.OData,代码行数:35,代码来源:HttpRequestMessageExtensions.cs

示例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;
        }
开发者ID:QuinntyneBrown,项目名称:wedding-bidders,代码行数:27,代码来源:MessageService.cs

示例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);
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:33,代码来源:BasicAuthHandler.cs


注:本文中的System.Net.Http.HttpRequestMessage.GetRequestContext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。