How to cast between WebRequest and HttpWebRequest


I was trying to open a website that returns a session cookie from X++ and I wanted to use CLR interop to achieve this.
So I needed to know how to use instance of HttpWebResponse class when X++ does not support casting from WebResponse class.


Solution is to use CLRObject to cast between WebRequest and HttpWebRequest.


static void Job_1(Args _args)
{
    System.Net.HttpWebRequest   httpRequest  = null;
    System.Net.HttpWebResponse  httpResponse = null;
    System.Net.CookieCollection cookies      = null;
    CLRObject                   clro         = null;
    ;
    new InteropPermission(InteropKind::ClrInterop).assert();
    clro         = System.Net.WebRequest::Create(“http://www.url.com/authenticate”);
    httpRequest  = clro;
    httpResponse = httpRequest.GetResponse();
    cookies      = httpResponse.get_Cookies();
    clro         = System.Net.WebRequest::Create(“http://www.url.com/”);
    httpRequest  = clro;
    httpResponse.set_Cookies(cookies);
    httpResponse = httpRequest.GetResponse();
}

Comments (3)

  1. Tommy says:

    This doesn’t compile. Isn’t the second last line supposed to be:

    httpResponse.set_Cookies(cookies);

  2. EMEAAXTec says:

    Hi Tommy

    Yes, you’re right!

    I’m sorry for the troubles this may have caused.

    I have corrected it now.

    Best regards,

    Daniel