控制器和控制器之间丢失的会话变量行动方法 [英] Session Variables Lost Between Controllers & Action Methods

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

问题描述

我在 ASP 中描述的场景几乎完全相同.NET MVC - 在控制器之间共享会话状态.问题是,如果我将图像的路径保存在 Session 变量 List 中,它不会在 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 中,我有 Upload() 操作方法:

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 中,我有 New() 操作方法,它具有以下代码:

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?

另外,我在考虑是否可以将负责上传图像的 ActionMethod 移动到 ItemController 并将图像路径存储在 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...

更新:

我已经更新了代码.另外我想我应该补充一点,我使用 StructureMap 作为我的控制器工厂.这可能是一个范围界定问题吗?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;
    }

有什么想法吗?

推荐答案

一个可能的原因是应用程序域在第一个和第二个操作之间重新启动,并且因为会话存储在内存中它会丢失.如果您在两者之间重新编译应用程序,则可能会发生这种情况.尝试在 Global.asax 的 Application_StartSession_Start 回调中放置一个断点,看看它们是否被调用了两次.

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天全站免登陆