C# (CSharp) ControllerContext примеры использования

C# (CSharp) ControllerContext - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для ControllerContext, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
		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);
		}
Пример #2
0
        /// <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 + ");");
            }
        }
Пример #3
0
 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);
     }
 }
 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));
     }
 }
        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);
            }
        }
Пример #6
0
        public QueueableViewAsPdf(ControllerContext context, string viewName)
        {
            _context = context;
            _viewName = viewName;

            ViewHtmlString = GetHtmlFromView();
        }
Пример #7
0
        /// <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;
        }
Пример #8
0
        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;
        }
Пример #9
0
 public Page_Context(ControllerContext controllerContext, PageRequestContext pageRequestContext)
 {
     this.ControllerContext = controllerContext;
     this.PageRequestContext = pageRequestContext;
     Styles = new List<IHtmlString>();
     Scripts = new List<IHtmlString>();
 }
        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;
        }
        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);
        }
        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;
        }
Пример #13
0
		//
		// 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);
		}
Пример #14
0
 /// <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;
 }
Пример #15
0
 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));
     }
 }
        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));
            }
        }
Пример #17
0
        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;
        }
Пример #18
0
        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();

            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }
Пример #19
0
        public QueueableViewAsPdf(ControllerContext context, object model)
        {
            _context = context;
            _model = model;

            ViewHtmlString = GetHtmlFromView();
        }
Пример #20
0
        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;
        }
 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();
 }
        public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (string.IsNullOrEmpty(viewName))
            {
                throw new ArgumentException("Value cannot be null or empty.", "viewName");
            }

            string[] viewLocationsSearched;
            string[] masterLocationsSearched;
            bool incompleteMatch = false;

            string controllerName = controllerContext.RouteData.GetRequiredString("controller");

            string viewPath = GetPath(controllerContext, ViewLocationFormats, AreaViewLocationFormats,
                                      "ViewLocationFormats", viewName, controllerName, cacheKeyPrefix_View, useCache,
                                      /* checkPathValidity */ true, ref incompleteMatch, out viewLocationsSearched);

            string masterPath = GetPath(controllerContext, MasterLocationFormats, AreaMasterLocationFormats,
                                        "MasterLocationFormats", masterName, controllerName, cacheKeyPrefix_Master,
                                        useCache, /* checkPathValidity */ false, ref incompleteMatch,
                                        out masterLocationsSearched);

            if (string.IsNullOrEmpty(viewPath) || (string.IsNullOrEmpty(masterPath) && !string.IsNullOrEmpty(masterName)))
            {
                return new ViewEngineResult(viewLocationsSearched.Union(masterLocationsSearched));
            }

            return new ViewEngineResult(CreateView(controllerContext, viewPath, masterPath), this);
        }
Пример #23
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ProjectNewViewModel model = (ProjectNewViewModel)bindingContext.Model ??
                (ProjectNewViewModel)DependencyResolver.Current.GetService(typeof(ProjectNewViewModel));
            bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
            string searchPrefix = (hasPrefix) ? bindingContext.ModelName + ".":"";

            //since viewmodel contains custom types like project make sure project is not null and to pass key arround for value providers
            //use Project.Name even if your makrup dont have Project prefix
            model.Project = new Project();
            //populate the fields of the model
            model.Project.ProjectId = 0;
            model.Project.Name = GetValue(bindingContext, searchPrefix, "Project.Name");
            model.Project.Url = GetValue(bindingContext, searchPrefix, "Project.Url");
            model.Project.CreatedOn  =  DateTime.Now;
            model.Project.UpdatedOn = DateTime.Now;
            model.Project.isDisabled = GetCheckedValue(bindingContext, searchPrefix, "Project.isDisabled");
            model.Project.isFeatured = GetCheckedValue(bindingContext, searchPrefix, "Project.isFeatured");
            model.Project.GroupId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.GroupId"));
            model.Project.Tags = new List<Tag>();

            foreach (var tagid in GetValue(bindingContext, searchPrefix, "Tags").Split(','))
            {
                var tag = new Tag { TagId = int.Parse(tagid)};
                model.Project.Tags.Add(tag);
            }

            var total = model.Project.Tags.Count;

            return model;
        }
        public void UsesSpecifiedBinder()
        {
            var controller = typeof(FromRouteAttr.SpecifiedBinderController);

             routes.Clear();
             routes.MapCodeRoutes(controller);

             var httpContextMock = new Mock<HttpContextBase>();
             httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/Foo/yes");

             var httpResponseMock = new Mock<HttpResponseBase>();
             httpContextMock.Setup(c => c.Response).Returns(httpResponseMock.Object);

             var routeData = routes.GetRouteData(httpContextMock.Object);

             var controllerInstance = (ControllerBase)Activator.CreateInstance(controller);
             controllerInstance.ValidateRequest = false;

             var requestContext = new RequestContext(httpContextMock.Object, routeData);
             var controllerContext = new ControllerContext(requestContext, controllerInstance);

             controllerInstance.ValueProvider = new ValueProviderCollection(new IValueProvider[] { new RouteDataValueProvider(controllerContext) });

             ((IController)controllerInstance).Execute(requestContext);

             httpResponseMock.Verify(c => c.Write(It.Is<string>(s => s == "True")), Times.AtLeastOnce());
        }
Пример #25
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
                throw new InvalidOperationException("Cannot update instances");

            if(controllerContext.RouteData.Values.ContainsKey("r"))
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.RouteData.Values["r"].ToString()
                           };
            }
            else if(controllerContext.HttpContext.Request.QueryString["r"] != null)
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.HttpContext.Request.QueryString["r"]
                           };
            }
            else if (controllerContext.HttpContext.Request.UrlReferrer != null)
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.HttpContext.Request.UrlReferrer.PathAndQuery
                           };
            }

            return new ReturnUrl();
        }
Пример #26
0
 public override void ExecuteResult(ControllerContext context)
 {
     if (context == null) throw new ArgumentNullException("context");
     HttpResponseBase response = context.HttpContext.Response;
     if (!string.IsNullOrWhiteSpace(_contenttype)) response.ContentType = _contenttype;
     response.OutputStream.Write(this._image, 0, this._image.Length);
 }
 public override void ExecuteResult(ControllerContext context)
 {
     context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
     base.ExecuteResult(context);
     context.HttpContext.Response.Write("</textarea></body></html>");
     context.HttpContext.Response.ContentType = "text/html";
 }
Пример #28
0
 public override void ExecuteResult(ControllerContext context)
 {
     context.HttpContext.Response.Clear();
     context.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
     context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.Public);
     if (id == -2)
     {
         context.HttpContext.Response.ContentType = "image/jpeg";
         context.HttpContext.Response.BinaryWrite(NoPic2());
     }
     else if (id == -2)
     {
         context.HttpContext.Response.ContentType = "image/jpeg";
         context.HttpContext.Response.BinaryWrite(NoPic1());
     }
     else
     {
         var i = ImageData.DbUtil.Db.Images.SingleOrDefault(ii => ii.Id == id);
         if (i == null)
         {
             context.HttpContext.Response.ContentType = "image/jpeg";
             context.HttpContext.Response.BinaryWrite(size == 1 ? NoPic1() : NoPic2());
         }
         else
         {
             context.HttpContext.Response.ContentType = i.Mimetype ?? "image/jpeg";
             context.HttpContext.Response.BinaryWrite(i.Bits);
         }
     }
 }
        // Executes the result (called by ASP.NET MVC).
        public override void ExecuteResult(ControllerContext context)
        {
            // Sanity check.
            if (context == null)
                throw new ArgumentNullException("context");

            // Get the current HTTP response, and clear it of content and headers.
            var response = context.HttpContext.Response;
            response.ClearHeaders();
            response.Clear();           // Intellisense says this clears headers, but it doesn't

            // Add do-not-cache headers to the response, but in a way that still allows IE to save the file.
            AddDoNotCacheHeadersToFileSaveResponse(response, context.HttpContext.Request);

            // Set the content type and disposition.
            response.ContentType = "text/csv";
            response.AddHeader("content-disposition", "attachment; filename=" + FileName);

            // Make sure the contents of the file are all sent at the same time.
            response.Buffer = true;

            // Use the Western code page 1252 encoding, which corresponds to the ISO-8859-1 standard.
            response.ContentEncoding = Encoding.GetEncoding(1252);

            // Write out the data.
            response.Write(CsvData);
        }
Пример #30
0
        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("JSON GET is not allowed");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;
            if (this.Data == null)
                return;

            var scriptSerializer = JsonSerializer.Create(this.Settings);

            scriptSerializer.Converters.Add(new CustomConverter());
            using (var sw = new StringWriter())
            {

                scriptSerializer.Serialize(sw, this.Data);
                response.Write(sw.ToString());
            }
        }