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

C# Mvc.ControllerContext类代码示例

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

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



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


示例16: Output

        public void Output(ControllerContext context, object resource, string contentType)
        {
            var outerStatusCode = context.RequestContext.HttpContext.Response.StatusCode;

            if (!context.Controller.GetType().Name.StartsWith("Partial"))
            {
                SetContentType(context, contentType);
            }

            var result = FindView(context, resource);
            if (result.View != null)
            {
                context.Controller.ViewData.Model = resource;

                result.View.Render(
                    new ViewContext(
                        context,
                        result.View,
                        context.Controller.ViewData,
                        new TempDataDictionary(),
                        context.HttpContext.Response.Output
                        ),
                    context.HttpContext.Response.Output
                    );
            }

            if(result.ViewEngine != null)
                result.ViewEngine.ReleaseView(context, result.View);

            context.RequestContext.HttpContext.Response.StatusCode = outerStatusCode;
        }
开发者ID:nhsevidence,项目名称:Snooze,代码行数:31,代码来源:ResourceTypeConventionViewFormatter.cs


示例17: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            CheckPropertyFilter(bindingContext);
            ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext);
            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName)
                && bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);
                binder = Providers.GetBinder(controllerContext, newBindingContext);
            }

            if (binder != null)
            {
                bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext);
                if (boundSuccessfully)
                {
                    // run validation and return the model
                    newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */);
                    return newBindingContext.Model;
                }
            }

            return null; // something went wrong
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:27,代码来源:ExtensibleModelBinderAdapter.cs


示例18: ExecuteResult

        /// <summary>
        /// Execute result
        /// </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("HttpMethot GET not allowed.");
            }

            var response = context.HttpContext.Response;
            var json = JsonConvert.SerializeObject(new { Type, Data },
                Formatting.Indented,
                new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

            response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

            if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;

            if (!string.IsNullOrEmpty(context.HttpContext.Request["callback"]))
            {
                json = string.Format("{0}({1})", context.HttpContext.Request["callback"], json);
            }

            context.HttpContext.Response.Write(json);

            base.ExecuteResult(context);
        }
开发者ID:adrianocaldeira,项目名称:thunder,代码行数:37,代码来源:JsonResult.cs


示例19: ExecuteResult

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = _contentType;

            response.OutputStream.Write(_bytes, 0, _bytes.Length);
        }
开发者ID:davidwhitney,项目名称:ImageProxyDotNet,代码行数:7,代码来源:RawBytesActionResult.cs


示例20: LogRequest

        private void LogRequest(ControllerContext actionContext, string context, string actName = "", string parameterList = "")
        {
            var request = actionContext.HttpContext.Request;
            var actionName = request.RawUrl ?? actName;

            try
            {
                string userName = (request.IsAuthenticated)
                    ? actionContext.HttpContext.User.Identity.Name
                    : request.Params["userName"];

                if(string.IsNullOrEmpty(actionName))
                 actionName = ActionName;

                var sessionId = request.Params["ASP.NET_SessionId"] + "-" + userName;

                Task.Run(
                    () =>
                        _logger.Log(
                            string.Format("{0} by UserName: {1}, ActionName: {2}, Params: {3}", context, userName, actionName, parameterList),
                            LogCategory.Verbose, sessionId));
            }
            catch
            {
            }
        }
开发者ID:Amit-khandelwal,项目名称:Amit_EmployeeFinder,代码行数:26,代码来源:LogAttribute.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Mvc.ControllerDescriptor类代码示例发布时间:2022-05-26
下一篇:
C# Mvc.ControllerBuilder类代码示例发布时间: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