Search code examples
c#.nethttp-postwebview2

Send Post-Request with WebView2 -> postData does not reach the API endpoint


I am using WebView2 (version 1.0.2365.46) in a WPF Application. I do have also a ASP.NET WebApp. I want to send a POST-Request to login in my WebApp from the WPF Application.

This is how I send the request on button click:

url = "https://localhost:5001/Account/LoginMachine";

var userData = new UserData()
{
    Username = "Test",
    Password = "abc"
};

var jsonString = JsonSerializer.Serialize(userData);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
    var request = webView.CoreWebView2.Environment.CreateWebResourceRequest(
        url,
        "POST",
        stream,
        "Content-Type: application/json");

    webView.CoreWebView2.NavigateWithWebResourceRequest(request);
}

And this is how my API endpoint looks like:

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> LoginMachine([FromBody] UserData userData)
{
    return Ok();
}

The userData at the API entpoint is always null.

What do I have to change to receive the userData at the API endpoint?


Solution

  • I have now solved this. I had to use HttpClient for this.

    These are the different steps I had to take to fulfill my requirements:

    1. Set the base URL (it would be better to set it as const for the whole class. But for this example it is also ok like this.):
    var baseUrl = "https://localhost:5001";
    
    1. Clean all old cookies (just for safety):
    var cookieListTask = webView.CoreWebView2.CookieManager.GetCookiesAsync(baseUrl);
    var cookieList = await cookieListTask;
    
    foreach (var cookie in cookieList)
    {
        webView.CoreWebView2.CookieManager.DeleteCookie(cookie);
    }
    
    1. Create final login URL and prepare login-data:
    var url = baseUrl + "/Account/LoginMachine";
    
    var userData = new UserData()
    {
        Username = "Test",
        Password = "abc"
    };
    
    var jsonString = JsonSerializer.Serialize(userData);
    var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
    
    1. Create HttpClientHandler:
    var handler = new HttpClientHandler();
    handler.CookieContainer = new CookieContainer();
    
    1. Create HttpClient and pass the handler:
    using (var client = new HttpClient(handler))
    {
    
    1. Send request:
    var response = await client.PostAsync(url, content);
    
    1. If request was successfull read response data, get cookies from handler and store new cookies in your webView instance:
    if (response.IsSuccessStatusCode)
    {
        string responseData = await response.Content.ReadAsStringAsync();
    
        var cookies = handler.CookieContainer.GetCookies(new Uri(baseUrl));
        foreach (Cookie cookie in cookies)
        {
    
            var tmpCookie = webView.CoreWebView2.CookieManager.CreateCookie(cookie.Name, cookie.Value, cookie.Domain, cookie.Path);
    
            webView.CoreWebView2.CookieManager.AddOrUpdateCookie(tmpCookie);
        }
        
    
    1. Redirect your client:
    webView.Source = new Uri("https://localhost:5001");
    
    1. Done:
        }
    }