• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ServiceModel.OperationContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.ServiceModel.OperationContext的典型用法代码示例。如果您正苦于以下问题:C# OperationContext类的具体用法?C# OperationContext怎么用?C# OperationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



OperationContext类属于System.ServiceModel命名空间,在下文中一共展示了OperationContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: DataFeed

        private List<string> _roles;   //Коллекция ролей пользователя. Служит для снижения нагрузки на базу данных при частых вызовах методов

        DataFeed()
        {
            _context = new EFDbContext();

            operationContext = OperationContext.Current;
            operationContext.Channel.Opened += Channel_Opened;
            operationContext.Channel.Closed += Channel_Closed;

            info = new Info();
            _uManager = new UManager(new UserStore<User>(new IdentityContext()));
            _user = _uManager.FindByName(operationContext.ServiceSecurityContext.PrimaryIdentity.Name); //Получаем текущего Identity пользователя 

            var roles = _uManager.GetUserRoles(_user.Id);  //Создадим список ролей пользователя к которым будем обращаться в методах для проверки, чтобы не загружать БД лишними запросами.

            _roles = roles.Select(r => r.Name).ToList();

            _conCount = roles.Max(r => r.NumberOfThreads);  //Установить максимальное количество потоков доступное из ролей данному пользователю

            _connector = GetAvialableConnector();
            _connector.ValuesChanged += Level1Changed;
            _connector.MarketDepthsChanged += Level2Changed;
            _connector.NewNews += NewNews;
            _connector.Error += Error;

            Console.WriteLine("SID: {0} ", operationContext.Channel.SessionId);

            _listener = new Listener(operationContext);

            //Запускаем вторичные потоки для обработки исторических данных
            for (int i = 0; i < _conCount; i++)
            {
                new Task(_listener.CandlesQueueStart).Start();
            }
        }
开发者ID:AlexandrKalinovskiy,项目名称:QService,代码行数:36,代码来源:DataFeed.cs


示例2: ParseHeader

        public static SIPSorcerySecurityHeader ParseHeader(OperationContext context)
        {
            try
            {
                int headerIndex = context.IncomingMessageHeaders.FindHeader(SECURITY_HEADER_NAME, SECURITY_NAMESPACE);
                if (headerIndex != -1)
                {
                    XmlDictionaryReader reader = context.IncomingMessageHeaders.GetReaderAtHeader(headerIndex);

                    if (reader.IsStartElement(SECURITY_HEADER_NAME, SECURITY_NAMESPACE))
                    {
                        reader.ReadStartElement();
                        reader.MoveToContent();

                        if (reader.IsStartElement(AUTHID_ELEMENT_NAME, SECURITY_NAMESPACE))
                        {
                            string authID = reader.ReadElementContentAsString();
                            return new SIPSorcerySecurityHeader(authID);
                        }
                    }
                }
                 return null;
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPSorcerySecurityHeader ParseHeader. " + excp.Message);
                throw;
            }
        }
开发者ID:akalafrancis,项目名称:sipsorcery-mono,代码行数:29,代码来源:SIPSorcerySecurityHeader.cs


示例3: CheckAccessCore

        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            string action = operationContext.RequestContext.RequestMessage.Headers.Action;

            Log.DebugFormat("Authentication in progress. Action: {0}", action);

            // Check globally anonymous actions..
            if (AnonymousActions.Contains(action))
            {
                Log.Debug("Request authorized as an Anonymous Action");
                return true;
            }

            if (Log.IsDebugEnabled)
            {
                int count = 0;
                foreach (IIdentity idt in operationContext.ServiceSecurityContext.GetIdentities())
                {
                    Log.DebugFormat("Identity{1}-{0}: {2}", idt.AuthenticationType, count++, idt.Name);
                }
            }

            if (operationContext.ServiceSecurityContext.AuthorizationContext.Properties.ContainsKey("Principal"))
            {
                Thread.CurrentPrincipal =
                    (IPrincipal)operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"];

                return base.CheckAccessCore(operationContext);
            }
            else
            {
                return false;
            }
        }
开发者ID:rag2111,项目名称:Hexa.Core,代码行数:34,代码来源:AuthorizationManager.cs


示例4: OperationContextPreservingSynchronizationContext

        /// <summary>
        ///     Create a new operation-context-preserving synchronization context.
        /// </summary>
        /// <param name="operationContext">
        ///     The operation context to propagate.
        /// </param>
        public OperationContextPreservingSynchronizationContext(OperationContext operationContext)
        {
            if (operationContext == null)
                throw new ArgumentNullException("operationContext");

            _operationContext = operationContext;
        }
开发者ID:ytokas,项目名称:appacitive-dotnet-sdk,代码行数:13,代码来源:OperationContextPreservingSynchronizationContext.cs


示例5: CheckAccess

        // We will always get here before we executing the service facade
        public override bool CheckAccess(OperationContext operationContext, ref Message message)
        {
            // This service is for techers only
            // The function will look at all the claims of type http://schemas.microsoft.com/ws/2008/06/identity/claims/role

            return Thread.CurrentPrincipal.IsInRole("Teacher");
        }
开发者ID:gooster,项目名称:WCFHostWIF45,代码行数:8,代码来源:MyServiceAuthorizationManager.cs


示例6: ParseHeader

        public static PullNotificationHeader ParseHeader(OperationContext context)
        {
            try
            {
                int headerIndex = context.IncomingMessageHeaders.FindHeader(NOTIFICATION_HEADER_NAME, PULL_NOTIFICATION_NAMESPACE);
                if (headerIndex != -1)
                {
                    XmlDictionaryReader reader = context.IncomingMessageHeaders.GetReaderAtHeader(headerIndex);

                    if (reader.IsStartElement(NOTIFICATION_HEADER_NAME, PULL_NOTIFICATION_NAMESPACE))
                    {
                        reader.ReadStartElement();
                        reader.MoveToContent();

                        if (reader.IsStartElement(ADDRESS_ELEMENT_NAME, PULL_NOTIFICATION_NAMESPACE))
                        {
                            string address = reader.ReadElementContentAsString();
                            return new PullNotificationHeader(address);
                        }
                    }
                }
                return null;
            }
            catch (Exception excp)
            {
                logger.Error("Exception PullNotificationHeader ParseHeader. " + excp.Message);
                throw;
            }
        }
开发者ID:TilmannBach,项目名称:sipsorcery-fork,代码行数:29,代码来源:PullNotificationHeader.cs


示例7: CheckAccessCore

        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            string action = operationContext.RequestContext.RequestMessage.Headers.Action;

            // parse the name of the operation that it is being invoked.
            string operationName = action.Substring(action.LastIndexOf('/') + 1);

            var httpRequest = operationContext.IncomingMessageProperties["httpRequest"] as HttpRequestMessageProperty;
            var authorizationHeader = httpRequest.Headers["Authorization"];

            if (string.IsNullOrEmpty(authorizationHeader))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            string user;
            string password;

            this.ParseUserPasswordFromHeader(authorizationHeader, out user, out password);

            if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            var authorizationService = ObjectFactory.GetInstance<IAuthorizationService>();

            if (!authorizationService.Authorize(user, operationName))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            return true;
        }
开发者ID:luismdcp,项目名称:PROMPT-06-Services,代码行数:34,代码来源:CustomAuthorizationManager.cs


示例8: CheckAccess

        public override bool CheckAccess(OperationContext operationContext, ref Message message)
        {
            base.CheckAccess(operationContext, ref message);
            string action = operationContext.IncomingMessageHeaders.Action;

            if (action == "urn:msdnmag/IService/GetRoles")
            {
                // messags in WCF are always read-once
                // we create one copy to work with, and one copy to return back to the plumbing
                MessageBuffer buffer = operationContext.RequestContext.RequestMessage.CreateBufferedCopy(int.MaxValue);
                message = buffer.CreateMessage();

                // get the username vale using XPath
                XPathNavigator nav = buffer.CreateNavigator();
                StandardNamespaceManager nsm = new StandardNamespaceManager(nav.NameTable);
                nsm.AddNamespace("msdn", "urn:msdnmag");

                XPathNavigator node =
                    nav.SelectSingleNode("s:Envelope/s:Body/msdn:GetRoles/msdn:username", nsm);
                string parameter = node.InnerXml;

                // check authorization
                if (operationContext.ServiceSecurityContext.PrimaryIdentity.Name == parameter)
                {
                    return true;
                }
                else
                {
                    return (GetPrincipal(operationContext).IsInRole("administrators"));
                }
            }

            return true;
        }
开发者ID:calderonsteven,项目名称:Preparation_For_Exam70-513,代码行数:34,代码来源:AuthorizationManager.cs


示例9: OperationContextScope

		public OperationContextScope (OperationContext context)
		{
			if (context == null)
				throw new ArgumentNullException ("context");
			previous = OperationContext.Current;
			OperationContext.Current = context;
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:OperationContextScope.cs


示例10: CheckAccessCore

        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] =
                Thread.CurrentPrincipal;

            return base.CheckAccessCore(operationContext);
        }
开发者ID:vendettamit,项目名称:PatternsFun,代码行数:7,代码来源:RestAuthorizationManager.cs


示例11: CheckAccessCore

 protected override bool CheckAccessCore(OperationContext operationContext)
 {
     //LocDHT: need this to avoid Evaluate exception
     operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = System.Threading.Thread.CurrentPrincipal;
     // If this point is reached, return false to deny access.
     return true;
 }
开发者ID:locdht,项目名称:MyVinaGerman,代码行数:7,代码来源:PersonnelAuthorizationManager.cs


示例12: OperationContextScope

 public OperationContextScope(OperationContext context)
 {
     this.originalContext = OperationContext.Current;
     this.originalScope = currentScope;
     this.thread = Thread.CurrentThread;
     this.PushContext(context);
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:OperationContextScope.cs


示例13: CheckAccess

        public override bool CheckAccess(OperationContext operationContext)
        {
            if(HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Contains("authservice")) { return true; }

            var token = GetToken(operationContext);

            if(AuthManager.ValidateToken(token))
            {
                var principal = AuthManager.GetPrincipal(token);
                var roles = Roles.GetRolesForUser(principal.Username);

                CurrentUser = new AuthUser()
                {
                    Identity = new AuthIdentity()
                    {
                        IsAuthenticated = true,
                        Name = principal.Username,
                        _id = principal.MemberID.ToString()
                    },
                    Principal = principal,
                    Roles = roles
                };

                return true;
            }

            return false;
        }
开发者ID:MPCC,项目名称:MPCC,代码行数:28,代码来源:ServiceAuthorization.cs


示例14: LockInstanceAfterCallout

        internal static void LockInstanceAfterCallout(OperationContext operationContext)
        {
            if (operationContext != null)
            {
                InstanceContext instanceContext = operationContext.InstanceContext;

                if (operationContext.IsServiceReentrant)
                {
                    ConcurrencyInstanceContextFacet resource = instanceContext.Concurrency;
                    ThreadWaiter waiter = null;

                    lock (instanceContext.ThisLock)
                    {
                        if (!resource.Locked)
                        {
                            resource.Locked = true;
                        }
                        else
                        {
                            waiter = new ThreadWaiter();
                            resource.EnqueueCalloutMessage(waiter);
                        }
                    }

                    if (waiter != null)
                    {
                        waiter.Wait();
                    }
                }
            }
        }
开发者ID:shijiaxing,项目名称:wcf,代码行数:31,代码来源:ConcurrencyBehavior.cs


示例15: CheckAccessCore

        /// <summary>
        /// Checks authorization for the given operation context based on policy evaluation.
        /// </summary>
        /// <param name="operationContext">
        /// The operation context. 
        /// </param>
        /// <returns>
        /// true if authorized, false otherwise 
        /// </returns>
        protected override bool CheckAccessCore( OperationContext operationContext )
        {
            var canAccess = false;

            var applicationVirtualRoot = HostingEnvironment.ApplicationVirtualPath;

            if ( applicationVirtualRoot == null )
            {
                throw new ArgumentException ( "The application virtual root could not be found for the current environment." );
            }

            // Remove the deployment environment specific application virtual root from the front of the resource request identifier.
            var path = applicationVirtualRoot.Equals ( @"/" )
                           ? operationContext.EndpointDispatcher.EndpointAddress.Uri.LocalPath
                           : operationContext.EndpointDispatcher.EndpointAddress.Uri.LocalPath.Remove ( 0, applicationVirtualRoot.Length );

            var currentClaimsPrincipalService = IoC.CurrentContainer.Resolve<ICurrentClaimsPrincipalService> ();
            var principal = currentClaimsPrincipalService.GetCurrentPrincipal ();

            if ( principal.Identity.IsAuthenticated )
            {
                var accessControlManager = IoC.CurrentContainer.Resolve<IAccessControlManager> ();
                canAccess = accessControlManager.CanAccess ( new ResourceRequest { path } );
            }
            else
            {
                Logger.Debug ( string.Format ( "Access to service '{0}' is denied because the principal is not authenticated.", path ) );
            }

            return canAccess;
        }
开发者ID:divyang4481,项目名称:REM,代码行数:40,代码来源:ServiceAuthorizationManager.cs


示例16: OnGetCreationContext

 protected override WorkflowCreationContext OnGetCreationContext(object[] inputs, OperationContext operationContext, Guid instanceId, WorkflowHostingResponseContext responseContext)
 {
     WorkflowCreationContext creationContext = new WorkflowCreationContext();
     creationContext.CreateOnly = true;
     if (operationContext.IncomingMessageHeaders.Action.EndsWith("Create"))
     {
         Dictionary<string, object> arguments = (Dictionary<string, object>)inputs[0];
         if (arguments != null && arguments.Count > 0)
         {
             foreach (KeyValuePair<string, object> pair in arguments)
             {
                 creationContext.WorkflowArguments.Add(pair.Key, pair.Value);
             }
         }
         responseContext.SendResponse(instanceId, null);
     }
     else if (operationContext.IncomingMessageHeaders.Action.EndsWith("CreateWithInstanceId"))
     {
         Dictionary<string, object> arguments = (Dictionary<string, object>)inputs[0];
         if (arguments != null && arguments.Count > 0)
         {
             foreach (KeyValuePair<string, object> pair in arguments)
             {
                 creationContext.WorkflowArguments.Add(pair.Key, pair.Value);
             }
         }
     }
     else
     {
         throw new InvalidOperationException("Invalid Action: " + operationContext.IncomingMessageHeaders.Action);
     }
     return creationContext;
 }
开发者ID:tian1ll1,项目名称:WPF_Examples,代码行数:33,代码来源:CreationEndpoint.cs


示例17: ReadContent

 private void ReadContent(OperationContext context)
 {
     using (var reader = context.RequestContext.RequestMessage.GetReaderAtBodyContents())
     {
         Content = reader.ReadOuterXml();
     }
 }
开发者ID:Marusyk,项目名称:GldAPIProxy,代码行数:7,代码来源:Message.cs


示例18: CheckAccessCore

        /// <summary>
        /// Checks authorization for the given operation context based on default policy evaluation.
        /// </summary>
        /// <param name="operationContext">The <see cref="T:System.ServiceModel.OperationContext" /> for the current authorization request.</param>
        /// <returns>
        /// true if access is granted; otherwise, false. The default is true.
        /// </returns>
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            var retVal = base.CheckAccessCore(operationContext);

            SimpleWebToken token = null;

            if (retVal)
            {
                // Extract authorization data.
                var requestMessage = operationContext.RequestContext.RequestMessage;
                var httpDetails = requestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                var requestUri = WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.UriTemplateMatch != null ? WebOperationContext.Current.IncomingRequest.UriTemplateMatch.BaseUri : requestMessage.Headers.To;

                token = ReadAuthToken(httpDetails);
                retVal = token != null && IsValidToken(token, requestUri);
            }

            var securityContext = ServiceSecurityContext.Anonymous;
            ClaimsPrincipal principal = new GenericPrincipal(new GenericIdentity(String.Empty), new string[0]);
            var identity = principal.Identity;

            if (retVal)
            {
                var claims = token.Claims.Select(keyValuePair => new Claim(keyValuePair.Key, keyValuePair.Value));
                identity = new ClaimsIdentity(claims, "OAUTH-SWT");
                principal = new ClaimsPrincipal(identity);
                Thread.CurrentPrincipal = principal;
            }
            securityContext.AuthorizationContext.Properties["Principal"] = principal;
            securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { identity };
            operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext;

            return retVal;
            //return true;
        }
开发者ID:Wdovin,项目名称:vc-community,代码行数:42,代码来源:OAuthAuthorizationManager.cs


示例19: ResolvePermissionAttribute

        /// <summary>
        /// Resolve the accessing service and operation contract.
        /// </summary>
        /// <param name="operationContext"></param>
        /// <returns></returns>
        public static WCFLookupResult ResolvePermissionAttribute(OperationContext operationContext)
        {
            Type serviceImplType = operationContext.EndpointDispatcher.DispatchRuntime.Type;
            Type[] interfaceTypes = serviceImplType.GetInterfaces();

            if (WebOperationContext.Current.IncomingRequest.UriTemplateMatch == null)
                return null;

            object WCFLookupResult = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.Data;
            //string operationContractName = DataBinder.Eval(WCFLookupResult, "OperationName") as string;
            string operationContractName = WCFLookupResult.ToString() ;

            foreach (Type interfaceType in interfaceTypes)
            {
                object[] serviceContractAttributes = interfaceType.GetCustomAttributes(typeof(ServiceContractAttribute), true);
                if (serviceContractAttributes.Length == 0) continue;

                string serviceContractName = ((ServiceContractAttribute)serviceContractAttributes[0]).Name;
                MethodInfo operationMethod = GetOperationMethodByOperationContractName(interfaceType, operationContractName);
                if (operationMethod == null) continue;

                object[] permissionAttributes = operationMethod.GetCustomAttributes(typeof(PermissionAttribute), true);
                if (permissionAttributes.Length == 0) continue;

                return new WCFLookupResult(serviceContractName, operationContractName);
            }

            return null;
        }
开发者ID:TatumAndBell,项目名称:RapidWebDev-Enterprise-CMS,代码行数:34,代码来源:WCFOperationContextUtility.cs


示例20: CheckAccess

        public override bool CheckAccess(OperationContext operationContext, ref Message message)
        {
           var contractName = operationContext.EndpointDispatcher.ContractName; 
           if (contractName == "IMetadataExchange" || contractName == "IHttpGetHelpPageAndMetadataContract") 
           { 
               // support for MEX 
               return true; 
            }
             
            var digestState = new DigestAuthenticationState(operationContext, GetRealm(ref message));
            if (!digestState.IsRequestDigestAuth)
            {
                return UnauthorizedResponse(digestState);
            }

            string password;
            if (!GetPassword(ref message, digestState.Username, out password))
            {
                return UnauthorizedResponse(digestState);
            }

            digestState.Password = password;
            if (!digestState.Authorized || digestState.IsNonceStale)
            {
                return UnauthorizedResponse(digestState);
            }

            return Authorized(digestState, operationContext, ref message);
        }
开发者ID:roncain,项目名称:wcf,代码行数:29,代码来源:DigestServiceAuthorizationManager.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ServiceModel.OperationContextScope类代码示例发布时间:2022-05-26
下一篇:
C# ServiceModel.NetTcpBinding类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap