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?
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:
var baseUrl = "https://localhost:5001";
var cookieListTask = webView.CoreWebView2.CookieManager.GetCookiesAsync(baseUrl);
var cookieList = await cookieListTask;
foreach (var cookie in cookieList)
{
webView.CoreWebView2.CookieManager.DeleteCookie(cookie);
}
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");
var handler = new HttpClientHandler();
handler.CookieContainer = new CookieContainer();
using (var client = new HttpClient(handler))
{
var response = await client.PostAsync(url, content);
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);
}
webView.Source = new Uri("https://localhost:5001");
}
}