當前位置: 首頁>>代碼示例>>C#>>正文


C# Mvc.ControllerContext類代碼示例

本文整理匯總了C#中System.Web.Mvc.ControllerContext的典型用法代碼示例。如果您正苦於以下問題:C# ControllerContext類的具體用法?C# ControllerContext怎麽用?C# ControllerContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ControllerContext類屬於System.Web.Mvc命名空間,在下文中一共展示了ControllerContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: BindModel

                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
                    if (controllerContext == null) {
                        throw new ArgumentNullException("controllerContext");
                    }

                    return new FormCollection(controllerContext.HttpContext.Request.Form);
                }
開發者ID:ledgarl,項目名稱:Samples,代碼行數:7,代碼來源:FormCollection.cs

示例2: ExecuteResultAsync

 public async override Task ExecuteResultAsync(ControllerContext context)
 {
     ViewEngineResult result;
     var viewContext = InitializeView(context, out result);
     await viewContext.View.RenderAsync(viewContext, viewContext.Writer).ConfigureAwait(false);
     ReleaseView(context, result);
 }
開發者ID:AndreGleichner,項目名稱:aspnetwebstack,代碼行數:7,代碼來源:ViewResultBase.cs

示例3: ExecuteResult

        public override void ExecuteResult(ControllerContext context)
        {
            if (base.Content == null)
            {
                //使用IMessageHandler輸出
                if (_messageHandlerDocument == null)
                {
                    throw new Senparc.Weixin.Exceptions.WeixinException("執行WeixinResult時提供的MessageHandler不能為Null!", null);
                }

                if (_messageHandlerDocument.FinalResponseDocument == null)
                {
                    //throw new Senparc.Weixin.MP.WeixinException("FinalResponseDocument不能為Null!", null);
                }
                else
                {
                    context.HttpContext.Response.ClearContent();
                    context.HttpContext.Response.ContentType = "text/xml";

                    var xml = _messageHandlerDocument.FinalResponseDocument == null 
                                ? "" 
                                : _messageHandlerDocument.FinalResponseDocument
                                                         .ToString().Replace("\r\n", "\n"); //騰

                    using (MemoryStream ms = new MemoryStream())//迅
                    {//真
                        var bytes = Encoding.UTF8.GetBytes(xml);//的

                        context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);//很
                    }//疼
                }
            }
        }
開發者ID:CurryHan,項目名稱:WeiXinMPSDK,代碼行數:33,代碼來源:FixWeixinBugWeixinResult.cs

示例4: GetClientValidationRules

        /// <summary>
        /// When implemented in a class, returns client validation rules for that class.
        /// </summary>
        /// <param name="metadata">The model metadata.</param>
        /// <param name="context">The controller context.</param>
        /// <returns>
        /// The client validation rules for this validator.
        /// </returns>
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessageString ?? "Field invalid. Field can only contain alphanumeric characters: 'a-z', 'A-Z', '0-9'.", ValidationType = clientValidationRule };
            rule.ValidationParameters.Add("pattern", RootModuleConstants.AlphanumericExpression);

            yield return rule;
        }
開發者ID:vivekmalikymca,項目名稱:BetterCMS,代碼行數:15,代碼來源:DisallowNonAlphanumericAttribute.cs

示例5: FindActionMethod

        public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName)
        {
            Contract.Assert(controllerContext != null);

            if (controllerContext.RouteData != null)
            {
                MethodInfo target = controllerContext.RouteData.GetTargetActionMethod();
                if (target != null)
                {
                    // short circuit the selection process if a direct route was matched.
                    return target;
                }
            }

            List<MethodInfo> finalMethods = FindActionMethods(controllerContext, actionName, AliasedMethods, NonAliasedMethods);

            switch (finalMethods.Count)
            {
                case 0:
                    return null;

                case 1:
                    return finalMethods[0];

                default:
                    throw CreateAmbiguousMatchException(finalMethods, actionName);
            }  
        }
開發者ID:RhysC,項目名稱:aspnetwebstack,代碼行數:28,代碼來源:ActionMethodSelector.cs

示例6: BindModel

        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>
        /// The bound value.
        /// </returns>
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            FacebookClient client = _config.ClientProvider.CreateClient();
            dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                controllerContext.HttpContext,
                rawSignedRequest =>
                {
                    return client.ParseSignedRequest(rawSignedRequest);
                });
            if (signedRequest != null)
            {
                string accessToken = signedRequest.oauth_token;
                string userId = signedRequest.user_id;
                client.AccessToken = accessToken;
                return new FacebookContext
                {
                    Client = client,
                    SignedRequest = signedRequest,
                    AccessToken = accessToken,
                    UserId = userId,
                    Configuration = _config
                };
            }
            else
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);
            }

            return null;
        }
開發者ID:tlycken,項目名稱:aspnetwebstack,代碼行數:38,代碼來源:FacebookContextModelBinder.cs

示例7: BindModel

        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            //get the car from the session

            Cart cart = null;
            if (controllerContext.HttpContext.Session != null)
            {
                cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
            }

            //create the Cart if there wasn't one in the session data

            if(cart == null)
            {
                cart = new Cart();

                if (controllerContext.HttpContext.Session != null)
                {
                    controllerContext.HttpContext.Session[sessionKey] = cart;
                }
            }

            return cart;
        }
開發者ID:agbald02,項目名稱:SoundBarrierHunting,代碼行數:25,代碼來源:CartModelBinder.cs

示例8: GetValidators

        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) {
            _adaptersLock.EnterReadLock();

            try {
                List<ModelValidator> results = new List<ModelValidator>();

                if (AddImplicitRequiredAttributeForValueTypes &&
                        metadata.IsRequired &&
                        !attributes.Any(a => a is RequiredAttribute)) {
                    attributes = attributes.Concat(new[] { new RequiredAttribute() });
                }

                foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) {
                    DataAnnotationsModelValidationFactory factory;
                    if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) {
                        factory = DefaultAttributeFactory;
                    }
                    results.Add(factory(metadata, context, attribute));
                }

                return results;
            }
            finally {
                _adaptersLock.ExitReadLock();
            }
        }
開發者ID:consumentor,項目名稱:Server,代碼行數:26,代碼來源:DataAnnotationsModelValidatorProvider.cs

示例9: CanFormat

 public bool CanFormat(ControllerContext context, object resource, string mimeType)
 {
     return ((_targetMimeType == mimeType)
             || string.IsNullOrEmpty(_targetMimeType)
             || (alsoAcceptRequestsToFormat!=null&&alsoAcceptRequestsToFormat.Contains(mimeType)))
            && FindView(context, resource).View != null;
 }
開發者ID:nhsevidence,項目名稱:Snooze,代碼行數:7,代碼來源:ResourceTypeConventionViewFormatter.cs

示例10: ExecuteResult

        public override void ExecuteResult(ControllerContext controllerContext)
        {
            if (controllerContext != null)
            {
                var request = controllerContext.HttpContext.Request;
                object callback = request[CALLBACK_QUERYSTRING];
                if (callback == null)
                {
                    controllerContext.RouteData.Values.TryGetValue(CALLBACK_QUERYSTRING, out callback);
                }

                var hasCallback = !string.IsNullOrWhiteSpace(callback == null ? "" : callback as string);

                if (hasCallback)
                {
                    SetContentTypeIfEmpty();
                    var response = controllerContext.HttpContext.Response;

                    response.Write(callback);
                    response.Write("(");
                    base.ExecuteResult(controllerContext);
                    response.Write(")");
                }
                else
                {
                    base.ExecuteResult(controllerContext);
                }
            }
        }
開發者ID:adams549659584,項目名稱:MyWeb,代碼行數:29,代碼來源:JsonpResult.cs

示例11: ExecuteResult

        /// <summary>
        ///   El código es el mismo de ASP.NET MVC 3, cambie el método que escribe en el response
        ///   http://aspnet.codeplex.com/SourceControl/changeset/view/63930#266491
        /// </summary>
        /// <param name = "context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
                String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(
                    "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
            }

            var response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            } else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                var settings = new JsonSerializerSettings();
                settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                settings.Converters.Add(new IsoDateTimeConverter());
                response.Write(JsonConvert.SerializeObject(this.Data, Formatting.None, settings));
            }
        }
開發者ID:romartinez,項目名稱:sicemed,代碼行數:40,代碼來源:NewtonJsonResult.cs

示例12: BindModel

        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null) {
                throw new ArgumentNullException("bindingContext");
            }

            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // case 1: there was no <input ... /> element containing this data
            if (valueResult == null) {
                return null;
            }

            string value = valueResult.AttemptedValue;

            // case 2: there was an <input ... /> element but it was left blank
            if (String.IsNullOrEmpty(value)) {
                return null;
            }

            // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
            // then we need to remove these quotes put in place by the ToString() method.
            string realValue = value.Replace("\"", String.Empty);
            return Convert.FromBase64String(realValue);
        }
開發者ID:sztupy,項目名稱:monosystemwebmvc,代碼行數:25,代碼來源:ByteArrayModelBinder.cs

示例13: FindView

        ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache, bool partial)
        {
            if (controllerContext == null) throw new ArgumentNullException("controllerContext");

             RouteData routeData = controllerContext.RouteData;

             string baseLocation = routeData.DataTokens[DataTokenKeys.ViewsLocation] as string;

             ViewEngineResult result;

             if (!String.IsNullOrEmpty(baseLocation)) {

            string controller = routeData.GetRequiredString("controller");

            string location = String.Concat(baseLocation, "/", controller);

            routeData.Values["controller"] = location;

            result = (partial) ?
               this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache)
               : this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache);

            routeData.Values["controller"] = controller;

             } else {

            result = (partial) ?
               this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache)
               : this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache);
             }

             return result;
        }
開發者ID:brettveenstra,項目名稱:MvcCodeRouting,代碼行數:33,代碼來源:ViewEngineWrapper.cs

示例14: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
            User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;

            int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
            int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
            string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
            string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();

            IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);

            string[] splitIds = selectedProfilePictureIds.Split(',');
            List<int> selectedProfilePictures = new List<int>();

            foreach (string id in splitIds) {
                if (id != string.Empty) {
                    selectedProfilePictures.Add(Int32.Parse(id));
                }
            }

            return new PhotosModel() {
                UserId = myUserId,
                ProfilePictureURL = myProfilePictureURL,
                Photos = myPhotos,
                SelectedPhotos = selectedProfilePictures
            };
        }
開發者ID:henryksarat,項目名稱:Have-A-Voice,代碼行數:28,代碼來源:UserPicturesModelBinder.cs

示例15: BindModel

 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
     if (string.IsNullOrEmpty(stringified))
         return null;
     return Serializer.Deserialize(stringified, bindingContext.ModelType);
 }
開發者ID:josh28,項目名稱:TaskMaster,代碼行數:7,代碼來源:FromJsonAttribute.cs


注:本文中的System.Web.Mvc.ControllerContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。