在C#MVC项目中添加虚假httpContext的会话

时间:2010-11-16 13:44:09

标签: c# model-view-controller session httpcontext renderpartial

如何将会话添加到fakeContext?

我们为部分请求构建此函数,其中内容必须以字符串形式返回。 现在只有部分请求中没有会话。

我不能像fakeContext.Session = HttpContext.Current.Session

那样添加它们

有人提出建议吗?

    ///<summary>
    /// Invoke the partial request and return the result as a string.
    ///</summary>
    ///<param name="context">The controller context to use.</param>
    ///<returns>A string containing the result of the partial request.</returns>
    public String InvokeAsString(ControllerContext context)
    {
        var stringBuilder = new StringBuilder();
        //create memory writer used for httpresponse.
        var memoryWriter = new StringWriter(stringBuilder);
        //create a fake response
        var fakeResponse = new HttpResponse(memoryWriter);
        //create a fake context.
        var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
        var oldPrincipal = context.HttpContext.User;
        fakeContext.User = oldPrincipal;

        //create a fake controllercontext to use for the default invoke action.
        var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), context.RouteData, context.Controller);                        

        var oldContext = HttpContext.Current;
        HttpContext.Current = fakeContext;

        ManagedWebSessionContext.Bind(
            HttpContext.Current,
            SessionManager.SessionFactory.OpenSession(new Interceptor()));

        //perform the default invoke action.
        Invoke(fakeControllerContext);
        HttpContext.Current = oldContext;

        //Flush memory and return output 
        memoryWriter.Flush();
        var content = stringBuilder.ToString();

        return content;
    }

1 个答案:

答案 0 :(得分:5)

找到解决方案

fakeContext.Items.Add(“AspSession”,HttpContext.Current.Session);

通过这种方式,即使fakeContext.Session是readOnly

,您也可以更改会话