开发者

Add session to fake httpContext in C# MVC project

开发者 https://www.devze.com 2023-01-25 03:16 出处:网络
How can i add th开发者_如何学运维e session to a fakeContext ? This function have we build for partial request where the content must be returned as a string.

How can i add th开发者_如何学运维e session to a fakeContext ?

This function have we build for partial request where the content must be returned as a string. Only we don't have sessions now in the partial request.

And i can't add them like fakeContext.Session = HttpContext.Current.Session

Someone a suggestion ?

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


Found the solution

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

On this way you can change the session even as fakeContext.Session is readOnly

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号