失落的控制器和放大器之间的会话变量;操作方法: [英] Session Variables Lost Between Controllers & Action Methods

查看:185
本文介绍了失落的控制器和放大器之间的会话变量;操作方法:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎完全由纳通泰勒在<所描述的相同的情况下href="http://stackoverflow.com/questions/1258422/asp-net-mvc-sharing-session-state-between-controllers">ASP.NET MVC - 共享会话状态之间控制器。现在的问题是,如果我的路径保存到图像的会话变量中名单,其中,串&GT; 它不被定义回到ItemController所以所有的路径正在丧失。 。这里是我的设置:

I have almost exactly the same scenario described by Nathon Taylor in ASP.NET MVC - Sharing Session State Between Controllers. The problem is that if I save the path to the images inside a Session variable List<string> it is not being defined back in the ItemController so all the paths are being lost... Here's my setup:

里面ImageController我有上传()操作方法:

Inside ImageController I have the Upload() action method:

    public ActionResult Upload()
    {
        var newFile = System.Web.HttpContext.Current.Request.Files["Filedata"];
        string guid = Guid.NewGuid() + newFile.FileName;
        string itemImagesFolder = Server.MapPath(Url.Content("~/Content/ItemImages/"));
        string fileName = itemImagesFolder + "originals/" + guid;
        newFile.SaveAs(fileName);

        var resizePath = itemImagesFolder + "temp/";
        string finalPath;
        foreach (var dim in _dimensions)
        {
            var resizedPath = _imageService.ResizeImage(fileName, resizePath, dim.Width + (dim.Width * 10/100), guid);
            var bytes = _imageService.CropImage(resizedPath, dim.Width, dim.Height, 0, 0);
            finalPath = itemImagesFolder + dim.Title + "/" + guid;
            _imageService.SaveImage(bytes, finalPath);
        }
        AddToSession(guid);
        var returnPath = Url.Content("~/Content/ItemImages/150x150/" + guid);
        return Content(returnPath);
    }

    private void AddToSession(string fileName)
    {
        if(Session[SessionKeys.Images] == null)
        {
            var imageList = new List<string>();
            Session[SessionKeys.Images] = imageList;
        }
        ((List<string>)Session[SessionKeys.Images]).Add(fileName);
    }

然后我ItemController里面我有一个具有以下code中的新()操作方法:

Then inside my ItemController I have the New() action method which has the following code:

        List<string> imageNames;
        var images = new List<Image>();
        if (Session[SessionKeys.Images] != null) //always returns false
        {
            imageNames = Session[SessionKeys.Images] as List<string>;
            int rank = 1;
            foreach (var name in imageNames)
            {
                var img = new Image {Name = name, Rank = rank};
                images.Add(img);
                rank++;
            }
        }

好了,所以为什么会出现这种情况,如何解决这个问题呢?

Ok so why is this happening and how do I solve it?

另外,我在想我是否可以移动,负责处理图像的上传到ItemController的ActionMethod并存储在ItemController本身就是一个List属性里面的图片的路径,将实际工作?但请注意,该图片被上传,并通过一个AJAX请求照顾。然后,当用户提交的项目报名表,所有关于随着图像的项目的数据应保存到数据库中...

Also, I was thinking of whether I could move the ActionMethod that takes care of the upload of the images into the ItemController and store the image paths inside a List property on the ItemController itself, would that actually work? Note though, that images are being uploaded and taken care of via an AJAX request. Then when the user submits the item entry form, all the data about the Item along with the images should be saved to the database...

更新:

我已经更新了code。此外,我想我要补充一点,我用StructureMap为我的控制器factorory。难道是一个范围的问题吗?什么是通常使用StructureMap默认范围是什么?

I've updated the code. Also I think I should add that I'm using StructureMap as my controller factorory. Could it be a scoping issue? What is the default scope that is usually used by StructureMap?

public class StructureMapDependencyResolver : IDependencyResolver
{
    public StructureMapDependencyResolver(IContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType.IsAbstract || serviceType.IsInterface)
        {
            return _container.TryGetInstance(serviceType);
        }
        else
        {
            return _container.GetInstance(serviceType);
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.GetAllInstances<object>()

            .Where(s => s.GetType() == serviceType);
    }

    private readonly IContainer _container;
}

和在我的Global.asax文件:

And inside my Global.asax file:

    private static IContainer ConfigureStructureMap()
    {
        ObjectFactory.Configure(x =>
        {
            x.For<IDatabaseFactory>().Use<EfDatabaseFactory>();
            x.For<IUnitOfWork>().Use<UnitOfWork>();
            x.For<IGenericMethodsRepository>().Use<GenericMethodsRepository>();
            x.For<IUserService>().Use<UsersManager>();
            x.For<IBiddingService>().Use<BiddingService>();
            x.For<ISearchService>().Use<SearchService>();
            x.For<IFaqService>().Use<FaqService>();
            x.For<IItemsService>().Use<ItemsService>();
            x.For<IMessagingService>().Use<MessagingService>();
            x.For<IStaticQueriesService>().Use<StaticQueriesService>();
            x.For < IImagesService<Image>>().Use<ImagesService>();
            x.For<ICommentingService>().Use<CommentingService>();
            x.For<ICategoryService>().Use<CategoryService>();
            x.For<IHelper>().Use<Helper>();
            x.For<HttpContext>().HttpContextScoped().Use(HttpContext.Current);

            x.For(typeof(Validator<>)).Use(typeof(NullValidator<>));

            x.For<Validator<Rating>>().Use<RatingValidator>();
            x.For<Validator<TopLevelCategory>>().Use<TopLevelCategoryValidator>();
        });

        Func<Type, IValidator> validatorFactory = type =>
        {
            var valType = typeof(Validator<>).MakeGenericType(type);
            return (IValidator)ObjectFactory.GetInstance(valType);
        };

        ObjectFactory.Configure(x => x.For<IValidationProvider>().Use(() => new ValidationProvider(validatorFactory)));
        return ObjectFactory.Container;
    }

有什么想法?

推荐答案

的一个可能的原因是,第一和第二操作,并因为会话存储在存储器中时会丢失数据之间的应用程序域重新启动。如果重新编译两者的应用程序,这可能发生。尝试把一个断点在的Application_Start 在session_start 在Global.asax中的回调,看看他们被称为两次。

One possible reason for this is that the application domain restarts between the first and the second actions and because session is stored in memory it will be lost. This could happen if you recompile the application between the two. Try putting a breakpoints in the Application_Start and Session_Start callbacks in Global.asax and see if they are called twice.

这篇关于失落的控制器和放大器之间的会话变量;操作方法:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆