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

C# ControllerContext类代码示例

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

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



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

示例1: ExecuteResult

 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     HttpResponseBase 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 enumerable = Data as IEnumerable;
         if (enumerable != null)
         {
             Data = new {d = enumerable};
         }
         var serializer = new JavaScriptSerializer();
         response.Write(serializer.Serialize(Data));
     }
 }
开发者ID:jeffreypalermo,项目名称:mvc2inaction,代码行数:30,代码来源:SecureJsonResult.cs


示例2: Init

		public void Init()
		{
			var en = CultureInfo.CreateSpecificCulture("en");

			Thread.CurrentThread.CurrentCulture	= en;
			Thread.CurrentThread.CurrentUICulture = en;

			helper = new FormHelper();

			subscription = new Subscription();
			mock = new MockClass();
			months = new[] {new Month(1, "January"), new Month(1, "February")};
			product = new Product("memory card", 10, (decimal) 12.30);
			user = new SimpleUser();
			users = new[] { new SimpleUser(1, false), new SimpleUser(2, true), new SimpleUser(3, false), new SimpleUser(4, true) };
			mock.Values = new[] { 2, 3 };

			var controller = new HomeController();
			var context = new ControllerContext();

			context.PropertyBag.Add("product", product);
			context.PropertyBag.Add("user", user);
			context.PropertyBag.Add("users", users);
			context.PropertyBag.Add("roles", new[] { new Role(1, "a"), new Role(2, "b"), new Role(3, "c") });
			context.PropertyBag.Add("sendemail", true);
			context.PropertyBag.Add("confirmation", "abc");
			context.PropertyBag.Add("fileaccess", FileAccess.Read);
			context.PropertyBag.Add("subscription", subscription);
			context.PropertyBag.Add("months", months);
			context.PropertyBag.Add("mock", mock);

			helper.SetController(controller, context);
		}
开发者ID:smoothdeveloper,项目名称:Castle.MonoRail,代码行数:33,代码来源:FormHelperCheckboxFieldListTestCase.cs


示例3: ExecuteResult

 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((this.JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
     {
         throw new InvalidOperationException("JsonRequest_GetNotAllowed");
     }
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrEmpty(this.ContentType))
     {
         response.ContentType = this.ContentType;
     }
     else
     {
         response.ContentType = "application/json";
     }
     if (this.ContentEncoding != null)
     {
         response.ContentEncoding = this.ContentEncoding;
     }
     if (this.Data != null)
     {
         var json = JsonConvert.SerializeObject(this.Data, Formatting.Indented, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects });
         response.Write(json);
     }
 }
开发者ID:Epitomy,项目名称:CMS,代码行数:29,代码来源:Json_netResult.cs


示例4: ExecuteResult

        /// <summary>
        /// Enables processing of the result of an action method by a
        /// custom type that inherits from
        /// <see cref="T:System.Web.Mvc.ActionResult"/>.
        /// </summary>
        /// <param name="context">The context within which the
        /// result is executed.</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            HttpResponseBase response = context.HttpContext.Response;
            if (!String.IsNullOrEmpty(ContentType))
                response.ContentType = ContentType;
            else
                response.ContentType = "application/javascript";

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

            if (Callback == null || Callback.Length == 0)
            {
                Callback = context.HttpContext.
                  Request.QueryString["callback"];
            }

            if (Data != null)
            {
                // The JavaScriptSerializer type was marked as obsolete
                // prior to .NET Framework 3.5 SP1
                JavaScriptSerializer serializer =
                     new JavaScriptSerializer();
                string ser = serializer.Serialize(Data);
                response.Write(Callback + "(" + ser + ");");
            }
        }
开发者ID:the404,项目名称:bigline,代码行数:37,代码来源:JsonpFilterAttribute.cs


示例5: FindAction

        public ActionDescriptorCreator FindAction(ControllerContext controllerContext, string actionName)
        {
            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

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

            List<MethodInfo> finalMethods = ActionMethodSelector.FindActionMethods(controllerContext, actionName, AliasedMethods, NonAliasedMethods);
            
            switch (finalMethods.Count)
            {
                case 0:
                    return null;

                case 1:
                    MethodInfo entryMethod = finalMethods[0];
                    return GetActionDescriptorDelegate(entryMethod);

                default:
                    throw CreateAmbiguousActionMatchException(finalMethods, actionName);
            }
        }
开发者ID:RhysC,项目名称:aspnetwebstack,代码行数:32,代码来源:AsyncActionMethodSelector.cs


示例6: QueueableViewAsPdf

        public QueueableViewAsPdf(ControllerContext context, string viewName)
        {
            _context = context;
            _viewName = viewName;

            ViewHtmlString = GetHtmlFromView();
        }
开发者ID:stephenzeng,项目名称:Rotativa,代码行数:7,代码来源:QueueableViewAsPdf.cs


示例7: ResolveCulture

        /// <summary>
        /// Resolves the UI culture from different sources of filter context.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public static CultureInfo ResolveCulture(ControllerContext filterContext)
        {
            if (filterContext == null)
            {
                return Globalizer.GetPossibleImplemented(null);
            }

            // Priority 1: from a lang parameter in the query string
            string languageFromRoute = filterContext.RouteData.Values["lang"] != null
                ? filterContext.RouteData.Values["lang"].ToString()
                : string.Empty;
            if (!string.IsNullOrEmpty(languageFromRoute))
            {
                // Reuse UI Culture as it was set beforehand from Globalizer if CountryCulture fails
                var foundCulture = Globalizer.GetCountryCulture(languageFromRoute) ?? Thread.CurrentThread.CurrentUICulture;

                // TODO: Set in User preferences (if we will have one)
                filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(CultureCookieName) { Value = foundCulture.Name });
                return foundCulture;
            }

            // Priority 2: Get culture from user's preferences/settings (if appropriate)

            // Priority 3: Get culture from user's cookie
            HttpCookie languageCookie = filterContext.HttpContext.Request.Cookies[CultureCookieName];
            if (languageCookie != null)
            {
                string languageFromCookie = languageCookie.Value;
                if (!string.IsNullOrEmpty(languageFromCookie))
                {
                    CultureInfo cultureToSet;
                    try
                    {
                        cultureToSet = new CultureInfo(languageFromCookie);
                    }
                    catch
                    {
                        // Cookie is damaged or tampered with - setting same culture as already set for UI
                        cultureToSet = Thread.CurrentThread.CurrentUICulture;
                    }

                    return cultureToSet;
                }
            }

            // Priority 4: Get culture from user's browser
            string languageFromBrowser = CultureHelper.GetRequestLanguage(filterContext);
            if (!string.IsNullOrEmpty(languageFromBrowser))
            {
                // Reuse UI Culture as it was set beforehand from Globalizer if CountryCulture fails
                var foundCulture = Globalizer.GetCountryCulture(languageFromBrowser) ?? Thread.CurrentThread.CurrentUICulture;

                // TODO: Set in User preferences (if we will have one)
                filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(CultureCookieName) { Value = foundCulture.Name });
                return foundCulture;
            }

            // Just return same culture as UI culture, as it is set first.
            return Thread.CurrentThread.CurrentUICulture;
        }
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:64,代码来源:CultureHelper.cs


示例8: CreateModel

        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            string dataRuleTypeStr;

            string dataruleTypeName = !string.IsNullOrWhiteSpace(bindingContext.ModelName) ? (bindingContext.ModelName + ".DataRuleType") : "DataRuleType";

            dataRuleTypeStr = controllerContext.HttpContext.Request[dataruleTypeName];

            if (string.IsNullOrEmpty(dataRuleTypeStr))
            {
                return null;
            }
            var dataRuleInt = Int32.Parse(dataRuleTypeStr);
            DataRuleType dataRuleTypeEnum = (DataRuleType)dataRuleInt;
            object model = null;
            switch (dataRuleTypeEnum)
            {
                case DataRuleType.Folder:
                    model = new FolderDataRule();
                    break;
                case DataRuleType.Schema:
                    model = new SchemaDataRule();
                    break;
                case DataRuleType.Category:
                    model = new CategoryDataRule();
                    break;
            }
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            return model;
        }
开发者ID:jason1234,项目名称:CMS,代码行数:30,代码来源:DataRuleBinder.cs


示例9: Page_Context

 public Page_Context(ControllerContext controllerContext, PageRequestContext pageRequestContext)
 {
     this.ControllerContext = controllerContext;
     this.PageRequestContext = pageRequestContext;
     Styles = new List<IHtmlString>();
     Scripts = new List<IHtmlString>();
 }
开发者ID:Kooboo,项目名称:Ovaldi,代码行数:7,代码来源:Page_Context.cs


示例10: BindModel

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object result = null;
            var args = new BindModelEvent(controllerContext, bindingContext);
            StrixPlatform.RaiseEvent(args);

            if (args.IsBound)
            {
                result = args.Result;
            }
            else
            {
                result = base.BindModel(controllerContext, bindingContext);

                if (bindingContext.ModelMetadata.Container == null && result != null && result.GetType().Equals(typeof(string)))
                {
                    if (controllerContext.Controller.ValidateRequest)
                    {
                        int index;

                        if (IsDangerousString((string)result, out index))
                        {
                            throw new HttpRequestValidationException("Dangerous Input Detected");
                        }
                    }

                    result = GetSafeValue((string)result);
                }
            }

            return result;
        }
开发者ID:StrixIT,项目名称:StrixIT.Platform,代码行数:32,代码来源:StrixPlatformBinder.cs


示例11: OnPropertyValidating

        protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

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

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

            if (value is string && controllerContext.HttpContext.Request.ContentType.StartsWith(WebConstants.APPLICATIONJSON, StringComparison.OrdinalIgnoreCase))
            {
                if (controllerContext.Controller.ValidateRequest && bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
                {
                    int index;

                    if (IsDangerousString(value.ToString(), out index))
                    {
                        throw new HttpRequestValidationException("Dangerous Input Detected");
                    }
                }
            }

            return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
        }
开发者ID:StrixIT,项目名称:StrixIT.Platform,代码行数:32,代码来源:StrixPlatformBinder.cs


示例12: BindModel

        public object BindModel(ControllerContext controllerContext, 
            ModelBindingContext bindingContext)
        {
            // get the cart 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 silly cart
            return cart;
        }
开发者ID:necampanini,项目名称:mvcStack_practice_01,代码行数:25,代码来源:CartModelBinder.cs


示例13: Index

		//
		// GET: /Test/

		public ActionResult Index()
		{
			StringWriter sw = new StringWriter();
			IFileSystem files = N2.Context.Current.Resolve<IFileSystem>();
			List<ContentRegistration> expressions = new List<ContentRegistration>();
			foreach (var file in files.GetFiles("~/Dinamico/Themes/Default/Views/ContentPages/").Where(f => f.Name.EndsWith(".cshtml")))
			{
				var cctx = new ControllerContext(ControllerContext.HttpContext, new RouteData(), new ContentPagesController());
				cctx.RouteData.Values.Add("controller", "DynamicPages");
				var v = ViewEngines.Engines.FindView(cctx, file.VirtualPath, null);

				if (v.View == null)
					sw.Write(string.Join(", ", v.SearchedLocations.ToArray()));
				else
				{
					var temp = new ContentPage();
					cctx.RequestContext.RouteData.ApplyCurrentPath(new N2.Web.PathData(temp));
					var vdd = new ViewDataDictionary { Model = temp };
					var re = new ContentRegistration(new DefinitionMap().GetOrCreateDefinition(typeof(ContentPage)).Clone());
					N2.Web.Mvc.Html.RegistrationExtensions.SetRegistrationExpression(cctx.HttpContext, re);
					v.View.Render(new ViewContext(cctx, v.View, vdd, new TempDataDictionary(), sw), sw);
					expressions.Add(re);
				}
			}
			return View(expressions);
		}
开发者ID:meixger,项目名称:n2cms,代码行数:29,代码来源:TestController.cs


示例14: PrepareControllerContext

 /// <summary>
 /// Prepares the controller context.
 /// </summary>
 /// <returns>The controller context.</returns>
 public static ControllerContext PrepareControllerContext()
 {
     var requestContext = PrepareRequestContext();
     var controllerBase = MockRepository.GenerateStub<ControllerBase>();
     var controllerContext = new ControllerContext(requestContext, controllerBase);
     return controllerContext;
 }
开发者ID:DogaOztuzun,项目名称:BlogSharp,代码行数:11,代码来源:TestsHelper.cs


示例15: ExecuteResult

 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException("context");
     }
     if ((this.JsonRequestBehavior == System.Web.Mvc.JsonRequestBehavior.DenyGet)
         && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
     {
         throw new InvalidOperationException();
     }
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrEmpty(this.ContentType))
     {
         response.ContentType = this.ContentType;
     }
     else
     {
         response.ContentType = "application/json";
     }
     if (this.ContentEncoding != null)
     {
         response.ContentEncoding = this.ContentEncoding;
     }
     if (this.Data != null)
     {
         //IsoDateTimeConverter converter = new IsoDateTimeConverter();
         //converter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
         response.Write(JsonConvert.SerializeObject(this.Data, Newtonsoft.Json.Formatting.Indented, Settings));
     }
 }
开发者ID:hoomim,项目名称:ttb-protype,代码行数:31,代码来源:JsonResult.cs


示例16: ExecuteResult

        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(JsonRequest_GetNotAllowed);
            }

            HttpResponseBase 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 serializer = new JavaScriptSerializer { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
                response.Write(serializer.Serialize(Data));
            }
        }
开发者ID:DanHibbert,项目名称:PresentationGenerator,代码行数:32,代码来源:LargeJsonResult.cs


示例17: GetDictionaryModel

        protected virtual object GetDictionaryModel(ControllerContext controllerContext, Type modelType, IValueProvider valueProvider, string prefix)
        {
            List<KeyValuePair<object, object>> list = new List<KeyValuePair<object, object>>();

            bool numericIndex;
            IEnumerable<string> indexes = GetIndexes(prefix, valueProvider, out numericIndex);
            Type[] genericArguments = modelType.GetGenericArguments();
            Type keyType = genericArguments[0];
            Type valueType = genericArguments[1];

            foreach (var index in indexes)
            {
                string indexPrefix = prefix + "[" + index + "]";
                if (!valueProvider.ContainsPrefix(indexPrefix) && numericIndex)
                {
                    break;
                }
                string keyPrefix = indexPrefix + ".Key";
                string valulePrefix = indexPrefix + ".Value";
                object key = GetModel(controllerContext, keyType,
                                           valueProvider, keyPrefix);
                object value = GetModel(controllerContext, valueType,
                                           valueProvider, valulePrefix);
                list.Add(new KeyValuePair<object, object>(key, value));
            }
            object model = CreateModel(modelType);
            ReplaceHelper.ReplaceDictionary(keyType, valueType, model, list);
            return model;
        }
开发者ID:xiaohong2015,项目名称:.NET,代码行数:29,代码来源:DefaultModelBinder.cs


示例18: SetFakeControllerContext

        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();

            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }
开发者ID:sethwebster,项目名称:TweetHarbor,代码行数:7,代码来源:MvcMockHelpers.cs


示例19: BindModel

        public object BindModel(ControllerContext context, string modelName, Type modelType)
        {
            if (modelType.IsValueType || typeof(string) == modelType)
            {
                object instance;
                if (GetValueTypeInstance(context, modelName, modelType, out instance))
                {
                    return instance;
                }
                return Activator.CreateInstance(modelType);
            }

            object modelInstance = Activator.CreateInstance(modelType);
            foreach (PropertyInfo property in modelType.GetProperties())
            {
                if (!property.CanWrite || (!property.PropertyType.IsValueType && property.PropertyType != typeof(string)))
                {
                    continue;
                }
                object propertyValue;
                if (GetValueTypeInstance(context, property.Name, property.PropertyType, out propertyValue))
                {
                    property.SetValue(modelInstance, propertyValue, null);
                }
            }
            return modelInstance;
        }
开发者ID:kcly3027,项目名称:kyCMS,代码行数:27,代码来源:DefaultModelBinder.cs


示例20: ExecuteResult

 public override void ExecuteResult(ControllerContext context)
 {
     // Set the response code to 401.
     context.HttpContext.Response.StatusCode = 401;
     context.HttpContext.Response.Write("Session has expired. Please log in again!");
     context.HttpContext.Response.End();
 }
开发者ID:andrewolobo,项目名称:overtly-clutz3,代码行数:7,代码来源:AuthorisationFilter.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# ControllerType类代码示例发布时间:2022-05-24
下一篇:
C# Controller2D类代码示例发布时间: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