當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。