Reputation: 314
Using UWP/XAML, I'm trying to intercept WebView's POST (form and file upload) request by handling WebResourceRequested and get the contents to be saved, but the Content keep shows '<unbuffered>' in the Local Window and cannot be accessed. How can I get access to the Content?
private void WebView_WebResourceRequested(WebView sender, WebViewWebResourceRequestedEventArgs args)
{
if (request.Method.Method == "POST")
{
HttpStreamContent content = (HttpStreamContent) args.request.Content;
var contentBuffer = content.ReadAsBufferAsync().GetResults();
byte[] buffer = contentBuffer.ToArray();
}
}
Thank you very much.
Upvotes: 0
Views: 485
Reputation: 32775
UWP intercept Webview POST request and get the content
This is know issue in WebView1.
Currently, we provided a workaround that use ReadAsInputStreamAsync
to get request content and use fixed length to load buffer. Because it is un-seek stream. I tested with success on the simple repro sample we have.
private async void MyWebView_WebResourceRequested(WebView sender, WebViewWebResourceRequestedEventArgs args)
{
if (args.Request.Method.Method == "POST")
{
if (args.Request.Content != null)
{
var bodyStream = await args.Request.Content.ReadAsInputStreamAsync();
var buffer = new Windows.Storage.Streams.Buffer(4096);
await bodyStream.ReadAsync(buffer, 4096, Windows.Storage.Streams.InputStreamOptions.None);
var reader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);
var len = reader.UnconsumedBufferLength;
var body = reader.ReadString(len);
Debug.WriteLine($"Body from POST request: {body}");
}
}
}
Of course, this code will work as long as we provide a buffer large enough for the post data. Here a buffer of 4096 bytes is enough to get the entire data posted, for this sample.
Upvotes: 2