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

C# IServiceContext类代码示例

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

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



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

示例1: OnMethodAuthorizing

        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            string userId, signatureHash;
            DateTime timestamp;

            if (!TryGetRequestedSignature(serviceContext.Request, out userId, out signatureHash, out timestamp) ||
                String.IsNullOrWhiteSpace(userId) ||
                String.IsNullOrWhiteSpace(signatureHash))
            {
                serviceContext.Response.SetStatus(HttpStatusCode.Unauthorized, Global.Unauthorized);
                return BehaviorMethodAction.Stop;
            }

            if (!IsRequestedSignatureValid(serviceContext, signatureHash, timestamp))
            {
                serviceContext.Response.SetStatus(HttpStatusCode.Unauthorized, Global.Unauthorized);
                return BehaviorMethodAction.Stop;
            }

            string hashedServerSignature = HashSignature(serviceContext.Request, userId, GenerateServerSignature(serviceContext, userId, timestamp));

            return signatureHash == hashedServerSignature ? BehaviorMethodAction.Execute : BehaviorMethodAction.Stop;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:34,代码来源:HmacAuthenticationBehavior.cs


示例2: FormatRequest

        /// <summary>
        /// Deserializes HTTP message body data into an object instance of the provided type.
        /// </summary>
        /// <param name="context">The service context.</param>
        /// <param name="objectType">The object type.</param>
        /// <returns>The deserialized object.</returns>
        /// <exception cref="HttpResponseException">If the object cannot be deserialized.</exception>
        public virtual object FormatRequest(IServiceContext context, Type objectType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (objectType == typeof(object))
            {
                using (var streamReader = new StreamReader(context.Request.Body, context.Request.Headers.ContentCharsetEncoding))
                {
                    return new DynamicXDocument(streamReader.ReadToEnd());
                }
            }

            if (context.Request.Body.CanSeek)
            {
                context.Request.Body.Seek(0, SeekOrigin.Begin);
            }

            var reader = XmlReader.Create(new StreamReader(context.Request.Body, context.Request.Headers.ContentCharsetEncoding));

            return XmlSerializerRegistry.Get(objectType).Deserialize(reader);
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:36,代码来源:XmlFormatter.cs


示例3: Init

        public void Init(IServiceContext context)
        {
            Context = context;
            host = context.GetPlugin<WemosPlugin>();

            InitLastValues();
        }
开发者ID:KonstantinKolesnik,项目名称:SmartHub,代码行数:7,代码来源:WemosControllerBase.cs


示例4: PopulateDynamicObject

        private static dynamic PopulateDynamicObject(IServiceContext context)
        {
            dynamic instance = new DynamicResult();

            foreach (string key in context.Request.QueryString.Keys)
            {
                IList<string> values = context.Request.QueryString.GetValues(key);
                string propertyName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(key);

                try
                {
                    if (values.Count == 1)
                    {
                        instance.Add(propertyName, values[0]);
                    }
                    else
                    {
                        instance.Add(propertyName, values);
                    }
                }
                catch (ArgumentException)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest, Global.InvalidDynamicPropertyName);
                }
            }

            return instance;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:28,代码来源:FromUriAsComplexTypeAttribute.cs


示例5: OnMethodAuthorizing

        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            if (serviceContext.Cache == null)
            {
                throw new InvalidOperationException(Resources.Global.UnableToInitializeCache);
            }

            string remoteAddress = serviceContext.Request.ServerVariables.RemoteAddress;

            if (String.IsNullOrEmpty(remoteAddress))
            {
                return BehaviorMethodAction.Execute;
            }

            string cacheKey = String.Concat("throttle-", serviceContext.Request.Url.GetLeftPart(UriPartial.Path), "-", remoteAddress);

            if (serviceContext.Cache.Contains(cacheKey))
            {
                SetStatus((HttpStatusCode) 429, Resources.Global.TooManyRequests);
                return BehaviorMethodAction.Stop;
            }

            serviceContext.Cache.Add(cacheKey, true, DateTime.Now.AddMilliseconds(m_delayInMilliseconds), CachePriority.Low);
            return BehaviorMethodAction.Execute;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:36,代码来源:ThrottlingBehavior.cs


示例6: BindObject

        private object BindObject(string name, Type objectType, IServiceContext context)
        {
            string value = context.Request.Headers.TryGet(GetHeaderName(name));
            object changedValue;

            return SafeConvert.TryChangeType(value, objectType, out changedValue) ? changedValue : null;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:7,代码来源:FromHeaderAttribute.cs


示例7: OnMethodExecuting

        /// <summary>
        /// Called before a service method is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method executing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodExecuting(IServiceContext serviceContext, MethodExecutingContext behaviorContext)
        {
            serviceContext.Request.ResourceBag.LoggingEnabled = true;
            serviceContext.Response.Output.WriteFormat("Action '{0}' executing", behaviorContext.GetMethodName()).WriteLine(2);

            return BehaviorMethodAction.Execute;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:13,代码来源:LoggingBehavior.cs


示例8: MerchelloHelper

        /// <summary>
        /// Initializes a new instance of the <see cref="MerchelloHelper"/> class.
        /// </summary>
        /// <param name="serviceContext">
        /// The service context.
        /// </param>
        public MerchelloHelper(IServiceContext serviceContext)
        {
            Mandate.ParameterNotNull(serviceContext, "ServiceContext cannot be null");

            _queryProvider = new Lazy<ICachedQueryProvider>(() => new CachedQueryProvider(serviceContext));
            _validationHelper = new Lazy<IValidationHelper>(() => new ValidationHelper());
        }
开发者ID:ProNotion,项目名称:Merchello,代码行数:13,代码来源:MerchelloHelper.cs


示例9: Execute

        public async Task Execute(IResult result, IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (result == null)
            {
                return;
            }

            var asyncResult = result as IResultAsync;

            if (asyncResult != null)
            {
                await asyncResult.ExecuteAsync(context, context.Response.GetCancellationToken());
            }
            else
            {
                result.Execute(context);
            }

            TryDisposeResult(result);
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:25,代码来源:ResultInvoker.cs


示例10: PerformQuery

        /// <summary>
        /// Performs a query on a collection and returns the resulting collection of
        /// objects.
        /// </summary>
        /// <param name="context">The service context.</param>
        /// <param name="collection">The collection to perform the query on.</param>
        /// <returns>The resulting collection.</returns>
        public virtual IEnumerable PerformQuery(IServiceContext context, IQueryable collection)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (collection == null)
            {
                return null;
            }

            NameValueCollection queryString = context.Request.QueryString.ToNameValueCollection();
            TrySetMaxQueryResults(context, queryString);

            int count;

            List<object> filteredCollection = TryConvertToFilteredCollection(collection, queryString, out count);
            object filteredObject = filteredCollection.FirstOrDefault(o => o != null);
            Type objectType = filteredObject != null ? filteredObject.GetType() : typeof(object);

            if (Attribute.IsDefined(objectType, typeof(CompilerGeneratedAttribute), false))
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError, Global.UnsupportedObjectTypeForOData);
            }

            Tuple<int, int> range = GetContentRanges(queryString, count);

            TrySetContentRange(context, filteredCollection, range);

            return GenerateFilteredCollection(filteredCollection, objectType);
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:39,代码来源:Linq2RestODataProvider.cs


示例11: OnMethodExecuting

        /// <summary>
        /// Called before a service method is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method executing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodExecuting(IServiceContext serviceContext, MethodExecutingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            if (behaviorContext == null)
            {
                throw new ArgumentNullException("behaviorContext");
            }

            if (behaviorContext.Resource == null || m_validator == null)
            {
                return BehaviorMethodAction.Execute;
            }

            IReadOnlyCollection<ValidationError> validationErrors;

            if (!m_validator.IsValid(behaviorContext.Resource, out validationErrors))
            {
                serviceContext.GetHttpContext().Items[ResourceValidator.ValidationErrorKey] = new ResourceState(validationErrors);
            }

            return BehaviorMethodAction.Execute;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:32,代码来源:ValidationBehavior.cs


示例12: Execute

        /// <summary>
        /// Executes the result against the provided service context.
        /// </summary>
        /// <param name="context">The service context.</param>
        public virtual void Execute(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (Content == null)
            {
                return;
            }

            if (ClearOutput)
            {
                context.Response.Output.Clear();
            }

            SetContentType(context);
            context.Response.SetCharsetEncoding(context.Request.Headers.AcceptCharsetEncoding);
            
            OutputCompressionManager.FilterResponse(context);

            context.Response.Output.Write(Content);

            LogResponse();
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:30,代码来源:ContentResult.cs


示例13: FormatRequest

        /// <summary>
        /// Deserializes HTTP message body data into an object instance of the provided type.
        /// </summary>
        /// <param name="context">The service context.</param>
        /// <param name="objectType">The object type.</param>
        /// <returns>The deserialized object.</returns>
        /// <exception cref="HttpResponseException">If the object cannot be deserialized.</exception>
        public virtual object FormatRequest(IServiceContext context, Type objectType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (context.Request.Body.CanSeek)
            {
                context.Request.Body.Seek(0, SeekOrigin.Begin);
            }

            var streamReader = new StreamReader(context.Request.Body, context.Request.Headers.ContentCharsetEncoding);
            var serializer = JsonSerializerFactory.Create();
            var reader = new JsonTextReader(streamReader);

            if (objectType == typeof(object))
            {
                return serializer.Deserialize(reader);
            }

            return serializer.Deserialize(reader, objectType);
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:35,代码来源:JsonFormatter.cs


示例14: RegistrationManager

        internal RegistrationManager(
            IRegistrationContext registrationContext, 
            IModuleManager moduleManager,
            IPublicRegistrationService publicRegistrationService, 
            ISdkInformation sdkInformation,
            IEnvironmentInformation environmentInformation, 
            IServiceContext serviceContext,
            ISecureRegistrationService secureRegistrationService, 
            IConfigurationManager configurationManager,
            IEventBus eventBus, 
            IRefreshToken tokenRefresher, 
            ILogger logger,
			IJsonSerialiser serialiser)
        {
            _registrationContext = registrationContext;
            _moduleManager = moduleManager;
            _publicRegistrationService = publicRegistrationService;
            _sdkInformation = sdkInformation;
            _environmentInformation = environmentInformation;
            _serviceContext = serviceContext;
            _secureRegistrationService = secureRegistrationService;
            _configurationManager = configurationManager;
            _eventBus = eventBus;
            _tokenRefresher = tokenRefresher;
            _logger = logger;
			_serialiser = serialiser;
        }
开发者ID:Donky-Network,项目名称:DonkySDK-Xamarin-Modular,代码行数:27,代码来源:RegistrationManager.cs


示例15: BindObject

        private static object BindObject(string name, Type objectType, IServiceContext context)
        {
            string uriValue = context.Request.QueryString.TryGet(name);
            object changedValue;

            return SafeConvert.TryChangeType(uriValue, objectType, out changedValue) ? changedValue : null;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:7,代码来源:FromUriAttribute.cs


示例16: OnMethodAuthorizing

        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            if (RequiresSsl && AuthorizeConnection(serviceContext.Request) == BehaviorMethodAction.Stop)
            {
                SetStatusDescription(Resources.Global.HttpsRequiredStatusDescription);
                return BehaviorMethodAction.Stop;
            }

            AuthorizationHeader header;

            if (!AuthorizationHeaderParser.TryParse(serviceContext.Request.Headers.Authorization, serviceContext.Request.Headers.ContentCharsetEncoding, out header) ||
                !AuthenticationType.Equals(header.AuthenticationType, StringComparison.OrdinalIgnoreCase))
            {
                serviceContext.Response.SetStatus(HttpStatusCode.Unauthorized, Resources.Global.Unauthorized);
                GenerateAuthenticationHeader(serviceContext);
                return BehaviorMethodAction.Stop;
            }

            Credentials credentials = m_authorizationManager.GetCredentials(header.UserName);

            if (credentials == null || !String.Equals(header.Password, credentials.Password, StringComparison.Ordinal))
            {
                GenerateAuthenticationHeader(serviceContext);
                return BehaviorMethodAction.Stop;
            }

            serviceContext.User = new GenericPrincipal(new GenericIdentity(header.UserName, AuthenticationType), credentials.GetRoles());
            return BehaviorMethodAction.Execute;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:40,代码来源:BasicAuthenticationBehavior.cs


示例17: Bind

        /// <summary>
        /// Binds data from an HTTP body key value pair to a service method parameter.
        /// </summary>
        /// <param name="name">The service method parameter name.</param>
        /// <param name="objectType">The binded object type.</param>
        /// <param name="context">The service context.</param>
        /// <returns>The object instance with the data or null.</returns>
        public override object Bind(string name, Type objectType, IServiceContext context)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.Request.Headers.ContentType == null || context.Request.Headers.ContentType.IndexOf(FormDataMediaType, StringComparison.OrdinalIgnoreCase) < 0)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError, Resources.Global.UnsupportedFormData);
            }

            if (!String.IsNullOrWhiteSpace(Name))
            {
                name = Name.Trim();
            }

            return objectType.IsArray ? BindArray(name, objectType, context) : BindObject(name, objectType, context);
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:36,代码来源:FromBodyAttribute.cs


示例18: BindObject

        private static object BindObject(string name, Type objectType, IServiceContext context)
        {
            string value = context.GetHttpContext().Request.Form.Get(name);
            object changedValue;

            return SafeConvert.TryChangeType(value, objectType, out changedValue) ? changedValue : null;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:7,代码来源:FromBodyAttribute.cs


示例19: Execute

        /// <summary>
        /// Executes the result against the provided service context.
        /// </summary>
        /// <param name="context">The service context.</param>
        public virtual void Execute(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (Code == HttpStatusCode.NoContent)
            {
                context.Response.Output.Clear();
            }

            foreach (var header in ResponseHeaders)
            {
                context.Response.SetHeader(header.Key, header.Value);
            }

            if (!String.IsNullOrWhiteSpace(Description))
            {
                context.Response.SetStatus(Code, Description);
            }
            else
            {
                context.Response.SetStatus(Code);
            }
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:30,代码来源:StatusCodeResult.cs


示例20: OnMethodAuthorizing

        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            var ranges = IPAddressRange.GetConfiguredRanges(m_sectionName).ToList();

            if (ranges.Count == 0)
            {
                return BehaviorMethodAction.Stop;
            }

            bool isAllowed = false;

            foreach (var range in ranges)
            {
                if (range.IsInRange(serviceContext.GetHttpContext().Request.UserHostAddress))
                {
                    isAllowed = true;
                    break;
                }
            }

            return isAllowed ? BehaviorMethodAction.Execute : BehaviorMethodAction.Stop;
        }
开发者ID:dstarosta,项目名称:GitProjects,代码行数:33,代码来源:AclBehavior.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# IServiceFactory类代码示例发布时间:2022-05-24
下一篇:
C# IServiceContainer类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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