Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix WebView header APIs and behavior #31246

Merged
merged 3 commits into from
Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using Microsoft.Web.WebView2.Core;
Expand Down Expand Up @@ -73,7 +75,8 @@ private async Task InitializeWebView2()

if (TryGetResponseContent(eventArgs.Request.Uri, allowFallbackOnHostPage, out var statusCode, out var statusMessage, out var content, out var headers))
{
eventArgs.Response = environment.CreateWebResourceResponse(content, statusCode, statusMessage, headers);
var headerString = GetHeaderString(headers);
eventArgs.Response = environment.CreateWebResourceResponse(content, statusCode, statusMessage, headerString);
}
};

Expand All @@ -94,6 +97,9 @@ await _webview.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(@"
=> MessageReceived(new Uri(eventArgs.Source), eventArgs.TryGetWebMessageAsString());
}

private static string GetHeaderString(IDictionary<string, string> headers) =>
string.Join(Environment.NewLine, headers.Select(kvp => $"{kvp.Key}: {kvp.Value}"));

private void ApplyDefaultWebViewSettings()
{
// Desktop applications typically don't want the default web browser context menu
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
@page "/"
@using WebviewAppShared
// NOTE: The full namespace is included here to work around this bug: https://github.com/dotnet/aspnetcore/issues/30851
@* NOTE: The full namespace is included here to work around this bug: https://github.com/dotnet/aspnetcore/issues/30851 *@
@inject BlazorWpfApp.AppState AppState

<h3>Hello, world!</h3>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Microsoft.AspNetCore.Components.WebView.WebViewManager.Dispose() -> void
Microsoft.AspNetCore.Components.WebView.WebViewManager.MessageReceived(System.Uri! sourceUri, string! message) -> void
Microsoft.AspNetCore.Components.WebView.WebViewManager.Navigate(string! url) -> void
Microsoft.AspNetCore.Components.WebView.WebViewManager.RemoveRootComponentAsync(string! selector) -> System.Threading.Tasks.Task!
Microsoft.AspNetCore.Components.WebView.WebViewManager.TryGetResponseContent(string! uri, bool allowFallbackOnHostPage, out int statusCode, out string! statusMessage, out System.IO.Stream! content, out string! headers) -> bool
Microsoft.AspNetCore.Components.WebView.WebViewManager.TryGetResponseContent(string! uri, bool allowFallbackOnHostPage, out int statusCode, out string! statusMessage, out System.IO.Stream! content, out System.Collections.Generic.IDictionary<string!, string!>! headers) -> bool
Microsoft.AspNetCore.Components.WebView.WebViewManager.WebViewManager(System.IServiceProvider! provider, Microsoft.AspNetCore.Components.Dispatcher! dispatcher, System.Uri! appBaseUri, Microsoft.Extensions.FileProviders.IFileProvider! fileProvider, string! hostPageRelativePath) -> void
Microsoft.Extensions.DependencyInjection.ComponentsWebViewServiceCollectionExtensions
abstract Microsoft.AspNetCore.Components.WebView.WebViewManager.NavigateCore(System.Uri! absoluteUri) -> void
Expand Down
13 changes: 9 additions & 4 deletions src/Components/WebView/WebView/src/StaticContentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.FileProviders;
Expand All @@ -24,7 +25,7 @@ public StaticContentProvider(IFileProvider fileProvider, Uri appBaseUri, string
_hostPageRelativePath = hostPageRelativePath ?? throw new ArgumentNullException(nameof(hostPageRelativePath));
}

public bool TryGetResponseContent(string requestUri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out string headers)
public bool TryGetResponseContent(string requestUri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out IDictionary<string, string> headers)
{
var fileUri = new Uri(requestUri);
if (_appBaseUri.IsBaseOf(fileUri))
Expand Down Expand Up @@ -75,7 +76,7 @@ private bool TryGetFromFileProvider(string relativePath, out Stream content, out
if (fileInfo.Exists)
{
content = fileInfo.CreateReadStream();
contentType = GetResponseContentTypeOrDefault(fileInfo.PhysicalPath);
contentType = GetResponseContentTypeOrDefault(fileInfo.Name);
return true;
}
}
Expand Down Expand Up @@ -107,7 +108,11 @@ private static string GetResponseContentTypeOrDefault(string path)
? matchedContentType
: "application/octet-stream";

private static string GetResponseHeaders(string contentType)
=> $"Content-Type: {contentType}{Environment.NewLine}Cache-Control: no-cache, max-age=0, must-revalidate, no-store";
private static IDictionary<string, string> GetResponseHeaders(string contentType)
=> new Dictionary<string, string>()
{
{ "Content-Type", contentType },
{ "Cache-Control", "no-cache, max-age=0, must-revalidate, no-store" },
};
}
}
2 changes: 1 addition & 1 deletion src/Components/WebView/WebView/src/WebViewManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ protected void MessageReceived(Uri sourceUri, string message)
/// <param name="content">The response content</param>
/// <param name="headers">The response headers</param>
/// <returns><c>true</c> if the response can be provided; <c>false</c> otherwise.</returns>
protected bool TryGetResponseContent(string uri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out string headers)
protected bool TryGetResponseContent(string uri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out IDictionary<string, string> headers)
=> _staticContentProvider.TryGetResponseContent(uri, allowFallbackOnHostPage, out statusCode, out statusMessage, out content, out headers);

internal async Task AttachToPageAsync(string baseUrl, string startUrl)
Expand Down
140 changes: 140 additions & 0 deletions src/Components/WebView/WebView/test/StaticContentProviderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
using Xunit;

namespace Microsoft.AspNetCore.Components.WebView
{
public class StaticContentProviderTests
{
[Fact]
public void TryGetResponseContentReturnsCorrectContentTypeForNonPhysicalFile()
{
// Arrange
const string cssFilePath = "folder/file.css";
const string cssFileContent = "this is css";
var inMemoryFileProvider = new InMemoryFileProvider(
new Dictionary<string, string>
{
{ cssFilePath, cssFileContent },
});
var appBase = "fake://0.0.0.0/";
var scp = new StaticContentProvider(inMemoryFileProvider, new Uri(appBase), "fakehost.html");

// Act
Assert.True(scp.TryGetResponseContent(
requestUri: appBase + cssFilePath,
allowFallbackOnHostPage: false,
out var statusCode,
out var statusMessage,
out var content,
out var headers));

// Assert
var contentString = new StreamReader(content).ReadToEnd();
Assert.Equal(200, statusCode);
Assert.Equal("OK", statusMessage);
Assert.Equal("this is css", contentString);
Assert.True(headers.TryGetValue("Content-Type", out var contentTypeValue));
Assert.Equal("text/css", contentTypeValue);
}

private sealed class InMemoryFileProvider : IFileProvider
{
public InMemoryFileProvider(IDictionary<string, string> filePathsAndContents)
{
if (filePathsAndContents is null)
{
throw new ArgumentNullException(nameof(filePathsAndContents));
}

FilePathsAndContents = filePathsAndContents;
}

public IDictionary<string, string> FilePathsAndContents { get; }

public IDirectoryContents GetDirectoryContents(string subpath)
{
return new InMemoryDirectoryContents(this, subpath);
}

public IFileInfo GetFileInfo(string subpath)
{
return FilePathsAndContents
.Where(kvp => kvp.Key == subpath)
.Select(x => new InMemoryFileInfo(x.Key, x.Value))
.Single();
}

public IChangeToken Watch(string filter)
{
return null;
}

private sealed class InMemoryDirectoryContents : IDirectoryContents
{
private readonly InMemoryFileProvider _inMemoryFileProvider;
private readonly string _subPath;

public InMemoryDirectoryContents(InMemoryFileProvider inMemoryFileProvider, string subPath)
{
_inMemoryFileProvider = inMemoryFileProvider ?? throw new ArgumentNullException(nameof(inMemoryFileProvider));
_subPath = subPath ?? throw new ArgumentNullException(nameof(inMemoryFileProvider));
}

public bool Exists => true;

public IEnumerator<IFileInfo> GetEnumerator()
{
return
_inMemoryFileProvider
.FilePathsAndContents
.Where(kvp => kvp.Key.StartsWith(_subPath, StringComparison.Ordinal))
.Select(x => new InMemoryFileInfo(x.Key, x.Value))
.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

private sealed class InMemoryFileInfo : IFileInfo
{
private readonly string _filePath;
private readonly string _fileContents;

public InMemoryFileInfo(string filePath, string fileContents)
{
_filePath = filePath;
_fileContents = fileContents;
}

public bool Exists => true;

public long Length => _fileContents.Length;

public string PhysicalPath => null;

public string Name => Path.GetFileName(_filePath);

public DateTimeOffset LastModified => DateTimeOffset.Now;

public bool IsDirectory => false;

public Stream CreateReadStream()
{
return new MemoryStream(Encoding.UTF8.GetBytes(_fileContents));
}
}
}
}
}