Home > Back-end >  How to get json response with WebView2
How to get json response with WebView2

Time:01-22

I wanna get a json from the response's body of this API:

// http://localhost:3000/api/auth/[token]
export default function Auth(request, response) {
    response.status(200).json({ token: request.query})
}

Trying the WebView.CoreWebView2.WebResourceResponseReceived event fires just once and the event arg's request Uri parameter is "http://localhost:3000/favicon.ico".

How can I get the response content?

What I did:

public partial class SignInUserControl : UserControl
{
    public SignInUserControl()
    {
        InitializeComponent();
        InitWebView();
    }
    async void InitWebView()
    {
        await WebView.EnsureCoreWebView2Async(null);
        WebView.CoreWebView2.WebResourceResponseReceived  = CoreWebView2_WebResourceResponseReceived;
    }
    async void CoreWebView2_WebResourceResponseReceived(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e)
    {
        try
        {
            Stream stream = await e.Response.GetContentAsync();
            TextReader tr = new StreamReader(stream);
            string re = tr.ReadToEnd();
        }
        catch { }
    }
}

What I expect:

http://localhost:3000/api/auth/42sad87aWasFGAS
re = {"token":"42sad87aWasFGAS"} // From CoreWebView2_WebResourceResponseReceived method

ps: The WebViewer2 Control is working. So I don't think the problem is related to its initialization. working example

CodePudding user response:

The problem really was the WebView initialization.

  • Related