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.
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.
So it is available as input stream. I though it already has all the content sent in the buffer. Thanks. I'm glad it is still managed so I don't have to wait for WebView2.
But it cannot read content of uploaded file. I wonder if there is any workaround. Or it is not covered on HttpRequestMessage in the first place.
@yosimadsu, yep, I know that, I’m afraid the workaround can’t work that way. You need to size the buffer correctly before calling ReadAsync.
I've tried many things to get the http POST multipart to be read, but seems it is the limit of WebView control. Probably I do need to wait for WebView2 and try the same thing, or I have to make my own webview instead. Thanks.