mercredi 20 septembre 2017

Setting a cookie and HTTP headers in your WebView in a UWP application [WebView,C#]

In this post we will see how to set values in the header and the cookie of your WebView in a UWP application.

First we need a method to create a new WebView:

//Creating a new webview
private WebView NewWebView()
            var webView = new WebView(WebViewExecutionMode.SameThread);
            return webView;

To edit the HTTP header that will be called by the WebView, and because we are using HttpRequestMessage from the Windows.Web.Http namespace.  We will edit the header like we would normally by creating a HttpRequestMessage property and adding a header by using Headers.Add:

private HttpRequestMessage NewRequest(Uri url)
            var message = new HttpRequestMessage(HttpMethod.Get, url);
            //adding User Agent to header            
            message.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063");
            //adding Authorization to header
message.Headers.Add("Authorization", "Bearer xxxxxxxxxxxx"); return message; }

Next here is how we can set cookies for our WebView, make sur that for the HttpCookie(key, "", "/") you set the correct domain or it will not work. Make sur that you set all the value correct (if the cookie is for a third party then make sure that SetCookie is set to TRUE and not false).

private void SetCookieInWebView(string key, string value)
            Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
            Windows.Web.Http.HttpCookie cookie = new Windows.Web.Http.HttpCookie(key, "", "/");
            cookie.Value = value;
            filter.CookieManager.SetCookie(cookie, false);
And lastly is how you could for example use all of these methods together.

//creating a new WebView
MyWebView = NewWebView();

//Setting cookies
SetCookieInWebView("Key1", "xxxxxxxxxxxxxxx"); SetCookieInWebView("Key2", "aaaaaaaaaaaaaaaa"); SetCookieInWebView("Key3", "bbbbbbbbbbbb"); //creating http request message to send to the webview HttpRequestMessage request = NewRequest("http:// xxxxx .com"); //doing http call MyWebView.NavigateWithHttpRequestMessage(request);

Happy Coding!