Skip to content

Handle synchronous exceptions from partial #16679

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

Merged
merged 2 commits into from
Nov 1, 2019
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 @@ -55,7 +55,7 @@ public virtual async Task ExecuteAsync(ActionContext context, ContentResult resu
{
response.ContentLength = resolvedContentTypeEncoding.GetByteCount(result.Content);

using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
await using (var textWriter = _httpResponseStreamWriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
{
await textWriter.WriteAsync(result.Content);

Expand Down
2 changes: 1 addition & 1 deletion src/Mvc/Mvc.Razor/src/RazorView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,7 @@ private async Task RenderLayoutAsync(
{
// This means we're writing to a 'real' writer, probably to the actual output stream.
// We're using PagedBufferedTextWriter here to 'smooth' synchronous writes of IHtmlContent values.
using (var writer = _bufferScope.CreateWriter(context.Writer))
await using (var writer = _bufferScope.CreateWriter(context.Writer))
{
await bodyWriter.Buffer.WriteToAsync(writer, _htmlEncoder);
await writer.FlushAsync();
Expand Down
6 changes: 3 additions & 3 deletions src/Mvc/Mvc.ViewFeatures/src/ViewComponentResultExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ public virtual async Task ExecuteAsync(ActionContext context, ViewComponentResul

_writerFactory ??= context.HttpContext.RequestServices.GetRequiredService<IHttpResponseStreamWriterFactory>();

using (var writer = _writerFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
await using (var writer = _writerFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
{
var viewContext = new ViewContext(
context,
Expand All @@ -149,8 +149,8 @@ public virtual async Task ExecuteAsync(ActionContext context, ViewComponentResul
}
else
{
using var bufferingStream = new FileBufferingWriteStream();
using (var intermediateWriter = _writerFactory.CreateWriter(bufferingStream, resolvedContentTypeEncoding))
await using var bufferingStream = new FileBufferingWriteStream();
await using (var intermediateWriter = _writerFactory.CreateWriter(bufferingStream, resolvedContentTypeEncoding))
{
viewComponentResult.WriteTo(intermediateWriter, _htmlEncoder);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Mvc/Mvc.ViewFeatures/src/ViewExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ protected async Task ExecuteAsync(

OnExecuting(viewContext);

using (var writer = WriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
await using (var writer = WriterFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be fairly easy to write a unit test for this too. Basically we would write a test where the body of the view in https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.ViewFeatures/test/ViewExecutorTest.cs#L94-L97 throws and the test ensures that MVC does not perform a synchronous write to the HTTP response stream.

{
var view = viewContext.View;

Expand Down
38 changes: 38 additions & 0 deletions src/Mvc/Mvc.ViewFeatures/test/ViewExecutorTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,44 @@ public static TheoryData<MediaTypeHeaderValue, string, string> ViewExecutorSetsC
}
}

[Fact]
public async Task ExecuteAsync_ExceptionInSyncContext()
{
// Arrange
var view = CreateView((v) =>
{
v.Writer.Write("xyz");
throw new NotImplementedException("This should be raw!");
});

var context = new DefaultHttpContext();
var stream = new Mock<Stream>();
stream.Setup(s => s.CanWrite).Returns(true);

context.Response.Body = stream.Object;
var actionContext = new ActionContext(
context,
new RouteData(),
new ActionDescriptor());
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider());

var viewExecutor = CreateViewExecutor();

// Act
var exception = await Assert.ThrowsAsync<NotImplementedException>(async () => await viewExecutor.ExecuteAsync(
actionContext,
view,
viewData,
Mock.Of<ITempDataDictionary>(),
contentType: null,
statusCode: null)
);

// Assert
Assert.Equal("This should be raw!", exception.Message);
stream.Verify(s => s.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>()), Times.Never);
}

[Theory]
[MemberData(nameof(ViewExecutorSetsContentTypeAndEncodingData))]
public async Task ExecuteAsync_SetsContentTypeAndEncoding(
Expand Down
13 changes: 12 additions & 1 deletion src/Mvc/test/Mvc.FunctionalTests/TagHelpersTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ public async Task CanRenderViewsWithTagHelpers(string action)
#endif
}

[Fact]
public async Task GivesCorrectCallstackForSyncronousCalls()
{
// Regression test for https://github.com/aspnet/AspNetCore/issues/15367
// Arrange
var exception = await Assert.ThrowsAsync<HttpRequestException>(async () => await Client.GetAsync("http://localhost/Home/MyHtml"));

// Assert
Assert.Equal("Should be visible", exception.InnerException.InnerException.Message);
}

[Fact]
public async Task CanRenderViewsWithTagHelpersAndUnboundDynamicAttributes_Encoded()
{
Expand Down Expand Up @@ -318,4 +329,4 @@ public async Task EncodersPages_ReturnExpectedContent(string actionName)
#endif
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ public IActionResult Help()
return View();
}

public IActionResult MyHtml()
{
return View();
}

public IActionResult ViewComponentTagHelpers()
{
return View();
Expand Down
27 changes: 27 additions & 0 deletions src/Mvc/test/WebSites/TagHelpersWebSite/MyHtmlContent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// 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.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace TagHelpersWebSite
{
public class MyHtmlContent : IHtmlContent
{
private IHtmlHelper Html { get; }

public MyHtmlContent(IHtmlHelper html)
{
Html = html;
}

public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
#pragma warning disable MVC1000 // Use of IHtmlHelper.{0} should be avoided.
Html.Partial("_Test").WriteTo(writer, encoder);
#pragma warning restore MVC1000 // Use of IHtmlHelper.{0} should be avoided.
}
}
}
1 change: 1 addition & 0 deletions src/Mvc/test/WebSites/TagHelpersWebSite/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<ItemGroup>
<ProjectReference Include="..\RazorPagesClassLibrary\RazorPagesClassLibrary.csproj" />
</ItemGroup>

<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc" />
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@(new TagHelpersWebSite.MyHtmlContent(Html))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this just use @Html.Partial("_Test")? I'm not sure if the extra indirection is necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The extra indirection seems to be necessary. Tested it out and we don't get the Synchronous complain otherwise.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@{
throw new Exception("Should be visible");
}