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


C# Controllers.HttpActionContext类代码示例

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


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

示例1: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestMessage request = actionContext.Request;
            string query = request.RequestUri.Query.Substring(1);
            var parts = query.Split('&').ToList();
            bool foundExpand = false;
            for (int i = 0; i < parts.Count; i++)
            {
                string segment = parts[i];
                if (segment.StartsWith(ODataExpandOption, StringComparison.Ordinal))
                {
                    foundExpand = true;
                    parts[i] += "," + this.AlwaysExpand;
                    break;
                }
            }

            if (!foundExpand)
            {
                parts.Add(ODataExpandOption + this.AlwaysExpand);
            }

            UriBuilder modifiedRequestUri = new UriBuilder(request.RequestUri);
            modifiedRequestUri.Query = string.Join("&",
                                        parts.Where(p => p.Length > 0));
            request.RequestUri = modifiedRequestUri.Uri;
            base.OnActionExecuting(actionContext);
        }
开发者ID:shawnhellinckx,项目名称:TravelListTeamStupid,代码行数:28,代码来源:QueryableExpandAttribute.cs

示例2: OnAuthorizationAsync

    public override async Task OnAuthorizationAsync( HttpActionContext actionContext, CancellationToken cancellationToken )
    {

      if ( actionContext.ControllerContext.ControllerDescriptor.ControllerType == typeof( UserController ) || string.Equals( actionContext.ActionDescriptor.ActionName, "Test", StringComparison.OrdinalIgnoreCase ) )
        return;

      var request = actionContext.Request;

      string loginToken = null;

      if ( loginToken == null )
      {
        var authorization = request.Headers.Authorization;

        if ( authorization != null && authorization.Scheme == "Hello" )
          loginToken = authorization.Parameter;
      }

      if ( loginToken == null )
      {
        var cookie = request.Headers.GetCookies( "loginToken" ).SelectMany( c => c.Cookies );
        if ( cookie.Any() )
          loginToken = cookie.First().Value;

      }


      var userId = Host.UserService.GetUserID( loginToken );
      if ( userId == null )
        actionContext.Response = request.CreateErrorResponse( HttpStatusCode.Unauthorized, "Unauthorized" );

      else
        actionContext.Request.Properties["UserID"] = userId;
    }
开发者ID:h2h,项目名称:HelloWorld,代码行数:34,代码来源:MyAuthorizeFilter.cs

示例3: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ReflectedHttpActionDescriptor actionDescriptor = actionContext.ActionDescriptor as ReflectedHttpActionDescriptor;
            if (null == actionDescriptor)
            {
                base.OnActionExecuting(actionContext);
            }

            CacheKey key = new CacheKey(actionDescriptor.MethodInfo,actionContext.ActionArguments);
            object[] array = HttpRuntime.Cache.Get(key.ToString()) as object[];
            if (null == array)
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            object value = array.Any() ? array[0] : null;
            IHttpActionResult actionResult = value as IHttpActionResult;
            if (null != actionResult)
            {
                actionContext.Response = actionResult.ExecuteAsync(CancellationToken.None).Result;
                return;
            }
            actionContext.Response = actionDescriptor.ResultConverter.Convert(actionContext.ControllerContext, value);
        }
开发者ID:chenboyi081,项目名称:asp-net-web-api-2-samples,代码行数:25,代码来源:CacheAttribute.cs

示例4: AuthorizeUserRequest

        public static bool AuthorizeUserRequest(HttpActionContext context)
        {
            var configuration = NotificationServiceContext.Current.Configuration;
            var repository = configuration.StorageProvider;
            var message = context.Request;

            Endpoint requestedEndpoint = null;

            if (message.Method != HttpMethod.Delete)
            {
                var readTask = message.Content.ReadAsAsync<Endpoint>();
                readTask.Wait();

                var endpoint = readTask.Result;
                if (endpoint != null)
                {
                    requestedEndpoint = repository.Find(endpoint.ApplicationId, endpoint.TileId, endpoint.ClientId);
                }

                // Since the content is now disposed, we need to restore it so it reaches the action
                message.Content = new ObjectContent<Endpoint>(endpoint, context.ControllerContext.Configuration.Formatters[0]);
            }
            else
            {
                var applicationId = context.ControllerContext.RouteData.Values["applicationId"] as string;
                var tileId = context.ControllerContext.RouteData.Values["tileId"] as string;
                var clientId = context.ControllerContext.RouteData.Values["clientId"] as string;

                requestedEndpoint = repository.Find(applicationId, tileId, clientId);
            }

            return requestedEndpoint == null || requestedEndpoint.UserId == configuration.MapUsername(message);
        }
开发者ID:kirpasingh,项目名称:MicrosoftAzureTrainingKit,代码行数:33,代码来源:NotificationService.cs

示例5: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var parameters = actionContext.ActionDescriptor.GetParameters();

            foreach (var parameter in parameters)
            {
                object value = null;

                if (actionContext.ActionArguments.ContainsKey(parameter.ParameterName))
                    value = actionContext.ActionArguments[parameter.ParameterName];

                if (value != null)
                    continue;

                value = Activator.CreateInstance(parameter.ParameterType);
                actionContext.ActionArguments[parameter.ParameterName] = value;

                var bodyModelValidator = actionContext.ControllerContext.Configuration.Services.GetBodyModelValidator();
                var metadataProvider = actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider();

                bodyModelValidator.Validate(value, value.GetType(), metadataProvider, actionContext, string.Empty);
            }

            base.OnActionExecuting(actionContext);
        }
开发者ID:Bringan,项目名称:RedditRankedFlairs,代码行数:25,代码来源:RejectEmptyModelFilter.cs

示例6: OnActionExecuting

 public override void OnActionExecuting(HttpActionContext actionContext)
 {
     try
     {
         var headers = actionContext.Request.Headers;
         if (headers.Authorization != null)
         {
             if (headers.Authorization.Scheme == "Token")
             {
                 using (UserRepo repo = new UserRepo())
                 {
                     var result = repo.Auth(headers.Authorization.Parameter);
                     if (result == null)
                         throw new UnauthorizedException();
                     actionContext.ActionArguments.Add(KEY, result.Value);
                 }
             }
         }
         else
             throw new UnauthorizedException();
     }
     catch (UnauthorizedException)
     {
         actionContext.Response = new HttpResponseMessage
         {
             StatusCode = HttpStatusCode.Unauthorized,
         };
     }
 }
开发者ID:Kyeong-min,项目名称:graduation-work-webapi,代码行数:29,代码来源:AuthAttribute.cs

示例7: OnAuthorization

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Content != null &&
                actionContext.Request.Content.Headers.ContentType != null)
            {
                if (allowJson && 
                    actionContext.Request.Content.Headers.ContentType.MediaType == JsonMediaTypeFormatter.DefaultMediaType.MediaType)
                {
                    return;
                }
                
                if (allowFormUrlEncoded && 
                    actionContext.Request.Content.Headers.ContentType.MediaType == FormUrlEncodedMediaTypeFormatter.DefaultMediaType.MediaType)
                {
                    return;
                }

                var env = actionContext.Request.GetOwinEnvironment();
                var localization = env.ResolveDependency<ILocalizationService>();

                actionContext.Response = actionContext.Request.CreateResponse(
                    HttpStatusCode.UnsupportedMediaType, 
                    new { ErrorMessage = localization.GetMessage(MessageIds.UnsupportedMediaType) }
                );
            }
        }
开发者ID:nmeierpolys,项目名称:Thinktecture.IdentityServer.v3,代码行数:26,代码来源:PreventUnsupportedRequestMediaTypesAttribute.cs

示例8: ExecuteBindingAsync

        public virtual Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (_parameterBindings.Length == 0)
            {
                return TaskHelpers.Completed();
            }

            // First, make sure the actionBinding is valid before trying to execute it. This keeps us in a known state in case of errors.
            foreach (HttpParameterBinding parameterBinder in ParameterBindings)
            {
                if (!parameterBinder.IsValid)
                {
                    // Throwing an exception because the webService developer's action signature is bad.
                    // This exception will be caught and converted into a 500 by the dispatcher
                    return TaskHelpers.FromError(new InvalidOperationException(parameterBinder.ErrorMessage));
                }
            }

            if (_metadataProvider == null)
            {
                HttpConfiguration config = actionContext.ControllerContext.Configuration;
                _metadataProvider = config.Services.GetModelMetadataProvider();
            }

            // Execute all the binders.
            IEnumerable<Task> tasks = from parameterBinder in ParameterBindings select parameterBinder.ExecuteBindingAsync(_metadataProvider, actionContext, cancellationToken);
            return TaskHelpers.Iterate(tasks, cancellationToken, disposeEnumerator: false);
        }
开发者ID:chrissimon-au,项目名称:aspnetwebstack,代码行数:28,代码来源:HttpActionBinding.cs

示例9: ValidateObject

        internal static bool ValidateObject(object o, List<ValidationResultInfo> validationErrors, HttpActionContext actionContext)
        {
            // create a model validation node for the object
            ModelMetadataProvider metadataProvider = actionContext.GetMetadataProvider();
            string modelStateKey = String.Empty;
            ModelValidationNode validationNode = CreateModelValidationNode(o, metadataProvider, actionContext.ModelState, modelStateKey);
            validationNode.ValidateAllProperties = true;

            // add the node to model state
            ModelState modelState = new ModelState();
            modelState.Value = new ValueProviderResult(o, String.Empty, CultureInfo.CurrentCulture);
            actionContext.ModelState.Add(modelStateKey, modelState);

            // invoke validation
            validationNode.Validate(actionContext);

            if (!actionContext.ModelState.IsValid)
            {
                foreach (var modelStateItem in actionContext.ModelState)
                {
                    foreach (ModelError modelError in modelStateItem.Value.Errors)
                    {
                        validationErrors.Add(new ValidationResultInfo(modelError.ErrorMessage, new string[] { modelStateItem.Key }));
                    }
                }
            }

            return actionContext.ModelState.IsValid;
        }
开发者ID:marojeri,项目名称:aspnetwebstack,代码行数:29,代码来源:DataControllerValidation.cs

示例10: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string token;

            try
            {
                token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Missing Authorization-Token")
                };
                return;
            }

            try
            {
		// TODO: here we use simple membership provider, 
		// replace with your own authentication. 
                if (!WebSecurity.UserExists(RsaCrypto.Decrypt(token)))
                {
                    throw new Exception() ;
                }
                base.OnActionExecuting(actionContext);
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    Content = new StringContent("Unauthorized User")
                };
            }
        }
开发者ID:Konex,项目名称:asp.net-mvc,代码行数:35,代码来源:TokenValidationAttribute.cs

示例11: HandleUnauthorizedRequest

 protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
 {
     base.HandleUnauthorizedRequest(actionContext);
     if (actionContext.Request.Headers.Authorization != null) return;
     var headerValue = String.Format("Basic realm=\"{0}\"", realm);
     actionContext.Response.Headers.Add("WWW-Authenticate", headerValue);
 }
开发者ID:chenzuo,项目名称:Restival,代码行数:7,代码来源:RequireHttpBasicAuthorizationAttribute.cs

示例12: InternalActionExecuting

        public virtual void InternalActionExecuting(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            var contentType = actionContext.Request.Content.Headers.ContentType;
            if (contentType != null && contentType.MediaType != JsonApiFormatter.JSON_API_MIME_TYPE)
            {
                return;
            }

            if (actionContext.ActionArguments.Any(a => a.Value is UpdateDocumentTypeWrapper))
            {
                var argument = actionContext.ActionArguments.First(a => a.Value is UpdateDocumentTypeWrapper);
                var updateDocument = argument.Value as UpdateDocumentTypeWrapper;
                if (updateDocument != null)
                {
                    var resultType = updateDocument.Type.GetGenericArguments()[0];
                    var context = new Context
                    {
                        Configuration = configuration,
                        RoutePrefix = GetRoutePrefix(actionContext)
                    };

                    var result = jsonApiTransformer.TransformBack(updateDocument.UpdateDocument, resultType, context);
                    actionContext.ActionArguments[argument.Key] = result;
                }
            }
        }
开发者ID:FrontlineEducation,项目名称:Util-JsonApiSerializer,代码行数:26,代码来源:JsonApiActionFilter.cs

示例13: GetModelBindingContext

        private ModelBindingContext GetModelBindingContext(ModelMetadataProvider metadataProvider, HttpActionContext actionContext)
        {
            string name = Descriptor.ParameterName;
            Type type = Descriptor.ParameterType;

            string prefix = Descriptor.Prefix;

            IValueProvider vp = CreateValueProvider(this._valueProviderFactories, actionContext);

            if (_metadataCache == null)
            {
                Interlocked.Exchange(ref _metadataCache, metadataProvider.GetMetadataForType(null, type));
            }

            ModelBindingContext ctx = new ModelBindingContext()
            {
                ModelName = prefix ?? name,
                FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
                ModelMetadata = _metadataCache,
                ModelState = actionContext.ModelState,
                ValueProvider = vp
            };
            
            if (_validationNodeCache == null)
            {
                Interlocked.Exchange(ref _validationNodeCache, ctx.ValidationNode);
            }
            else
            {
                ctx.ValidationNode = _validationNodeCache;
            }

            return ctx;
        }
开发者ID:acprofessionale,项目名称:aspnetwebstack,代码行数:34,代码来源:ModelBinderParameterBinding.cs

示例14: OnActionExecuting

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var authHead = actionContext.Request.Headers.Authorization;
            if (authHead != null)
            {
                if (authHead.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authHead.Parameter != null)
                {
                    var credentials = Encoding.GetEncoding("iso-8859-1").GetString(Convert.FromBase64String(authHead.Parameter));

                    int separator = credentials.IndexOf(':');
                    string username = credentials.Substring(0, separator);
                    string password = credentials.Substring(separator + 1);

                    if (apiKeys.Contains(password))
                    {
                        IUserScopedController controller = actionContext.ControllerContext.Controller as IUserScopedController;
                        if (controller != null && !string.IsNullOrWhiteSpace(username))
                        {
                            controller.UserId = username;
                        }
                        return;
                    }
                }
            }

            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", actionContext.Request.RequestUri.Host));
        }
开发者ID:RainyBlueSky,项目名称:Azure-MachineLearning-DataScience,代码行数:28,代码来源:AuthorizeApiKeyAttribute.cs

示例15: ExecuteActionFilterAsync

        public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            if (actionContext.Request.Headers.Contains("X-AccessToken"))
            {
                var tokenvalue = actionContext.Request.Headers.GetValues("X-AccessToken").FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }
            else if (actionContext.Request.RequestUri.ParseQueryString() != null)
            {
                var queryValues = actionContext.Request.RequestUri.ParseQueryString();
                var tokenvalue = queryValues["token"];
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }

            return Task.Factory.StartNew(() =>
            {
                var retur = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("This resource cannot be used without the correct access token")
                };

                return retur;
            });

        }
开发者ID:unipluss,项目名称:UniAlltid.Language,代码行数:31,代码来源:TokenAccessFilter.cs


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