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(“”);
httpRequest  = clro;
httpResponse = httpRequest.GetResponse();
cookies      = httpResponse.get_Cookies();
clro         = System.Net.WebRequest::Create(“”);
httpRequest  = clro;
httpResponse = httpRequest.GetResponse();

We're always looking for feedback and would like to hear from you. Please head to the Dynamics 365 Community to start a discussion, ask questions, and tell us what you think!