Question

So a request is made to an ASP.net MVC controller/action. This has an associated session. Part of the action we instantiate a WebClient object and make a call to a resource that is on the same site.

However, despite the fact that it is the same site, same app pool, because the WebClient creates a new request it has a different session. (I know what your thinking, if it is on the same app pool, same site, why need the WebClient). I have left those details out to not muddy the water, but there is a reason for the WebClient.

It is my understanding, that if the WebClient could be assigned the cookies from original Request.Cookies collection, that ASP.net would be able to look up the existing Session based on the cookies existing.

So I guess there is 2 questions:

  1. Is this correct, and if I was to assign the cookies (somehow) to the WebClient that the Request created by the WebClient would end up acquiring the Session of the original request.
  2. How can I assign the current Request.Cookies to the WebClient?

UPDATE

I have looked at and tried both Using CookieContainer with WebClient class as well as Sending cookies using HttpCookieCollection and CookieContainer and I have not found a working solution.

We have a bundled Solution of Umbraco and asp.net MVC and we are using the webclient to make a request to Umbraco for a page. In my research I have also discovered that there could be other facts that might cause the cookies not to work as I described above. So I guess the first order of business it to find out if the whole bit about cookies would allow the original session to be obtained? Or if there is a better way to go about what we are doing?

Was it helpful?

Solution

Maybe you can try the implementation shown here:

Sending cookies using HttpCookieCollection and CookieContainer

It copies the incoming cookies to an outgoing external request. However, that implementation is for using HttpWebRequest. If you really need to use WebClient instead then this might be useful: Using CookieContainer with WebClient class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top