小编典典

控制器和操作方法之间丢失的会话变量

ajax

我几乎与Nathon Taylor在ASP.NET MVC-
控制器之间的共享会话状态中描述的场景完全相同。问题是,如果我将路径保存到Session变量中的图像List<string>,则不会在ItemController中定义它,因此所有路径都将丢失…这是我的设置:

在ImageController内部,我具有Upload()操作方法:

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

        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++;
            }
        }

好的,为什么会这样,我该如何解决?

另外,我还在考虑是否可以将负责将图像上载的ActionMethod移到ItemController中,并将图像路径存储在ItemController本身的List属性内,这是否有效?不过请注意,图像是通过AJAX请求上传和处理的。然后,当用户提交项目输入表单时,有关该项目的所有数据以及图像应保存到数据库中。

更新:

我已经更新了代码。另外我想我应该补充一点,我正在使用StructureMap作为我的控制器析因。可能是范围界定问题吗?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文件中:

    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;
    }

有什么想法吗?


阅读 201

收藏
2020-07-26

共1个答案

小编典典

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

2020-07-26