Giter Site home page Giter Site logo

aspnet / aspnetwebstack Goto Github PK

View Code? Open in Web Editor NEW
847.0 847.0 350.0 13.46 MB

ASP.NET MVC 5.x, Web API 2.x, and Web Pages 3.x (not ASP.NET Core)

License: Other

Batchfile 0.02% C# 97.41% CSS 0.11% JavaScript 0.01% HTML 0.96% Visual Basic .NET 1.41% VBScript 0.03% ASP.NET 0.05% PowerShell 0.01%

aspnetwebstack's People

Contributors

adjames avatar analogrelay avatar andreazevedo avatar anthonymoore avatar bradolenick avatar bradwilson avatar congysu avatar danroth27 avatar davidmatson avatar dotnet-bot avatar dotnetjunky avatar dougbu avatar eilon avatar grabyourpitchforks avatar grantmcdade avatar javiercn avatar kenegozi avatar marcind avatar mccalltd avatar mikestall avatar mlacouture avatar ntaylormullen avatar patrickmcdonald avatar perrytaylor avatar pranavkm avatar roncain avatar rynowak avatar vijayrkn avatar wtgodbe avatar xuzhg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnetwebstack's Issues

Update satellite package for Web API Client to contain all necessary resource assemblies

Our CI is set up to create locale-specific packages containing only .NET 4.5 assemblies. While the microsoft.aspnet.webapi.client.5.2.3.nupkg package contains both lib/net45 and lib/portable-wp8%2Bnetcore45%2Bnet45%2Bwp81%2Bwpa81 (originally lib\portable-wp8+netcore45+net45+wp81+wpa81), microsoft.aspnet.webapi.client.fr.5.2.3.nupkg contains only lib/net45.

Since some of the same resources are used client-side, should ship the portable satellite assemblies.

Newtonsoft.Json specific assembly reference is breaking my projects

Hello all,

I'm not sure if this is the right place, but I'm looking for the code-behind Microsoft.AspNet.WebApi. It seems that the reference to System.Net.Formatting makes a specific reference to Newtonsoft.Json, Version=6.0.0.0. I use bindingRedirects and it compiles, but at run-time if I try to hit the page I find myself in Dependency hell.

If you need Version 6.0.0.0, I suggest you set specificVersion to true to ensure that no one else finds themselves here after it compiles properly. If you don't need Version 6.0.0.0, Newtonsoft.Json is on version 10 now, could you please remove the specific reference details so that instead of saying reference="Newtonsoft.Json, Version 6.0.0.0...." It just says reference="Newtonsoft.Json"?

Or, please advise one what I should do to get out of dependency hell if no change is necessary.

System.Web.Mvc.HtmlHelper.RenderPartialInternal InvalidOperationException

A System.InvalidOperationException occurs when rendering a partial view by passing in the property of a view model to HtmlHelper.Partial, when that property is an uninitialized reference type (a null reference). The exception message takes the form:

The model item passed into the dictionary is of type '{type A}', but this dictionary requires a model item of type '{type B}'.

Type A above is the view model type, and type B is the type expected by the partial view.

I believe that this occurs because of line 527 in System.Web.Mvc.HtmlHelper

newViewData = new ViewDataDictionary(ViewData);

which attempts to initialize a new ViewDataDictionary using the HtmlHelper.ViewData, which refers to the view's model, not the model's property. Hence the type mismatch. This is incorrect and should be initialized using the null value passed in, as in line 538.

This is a duplicate of the bug I reported at https://connect.microsoft.com/VisualStudio/feedback/EditFeedback.aspx?FeedbackID=3140000

Add `FormUrlEncodedMediaTypeFormatter` to client formatting assemblies

Creating new work to track work @YakhontovYaroslav has done in #76.

Use case

Copied from #4 (comment) with a few edits:

I'm talking about https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedMediaTypeFormatter.cs this class. Its included in https://github.com/aspnet/AspNetWebStack/tree/master/src/System.Net.Http.Formatting , but missing from https://github.com/aspnet/AspNetWebStack/tree/master/src/System.Net.Http.Formatting.NetStandard and Core versions.

I'm not looking for server side implementation. As i mentioned above, we are using this formatter (as well as Json and Xml from same namespace) to dynamically build HttpClient pipelines using DelegatingHandler and Castle.Core proxies. Its neat way to declare whole serialization\deserialization pipelines using just interface declaration with custom attributes like ContentType, Accept, Route, Method etc. Many 3rd party APIs still uses FormUrlEncoded in POST and GET requests, and we must somehow integrate with them. Removing FormUrlEncodedMediaTypeFormatter from Microsoft.AspNet.WebApi.Client package will force us (and many people who used it similar way) to create our own implementation of FormData formatter, which seems unnecessary, when package already contains this functionality, which can be easily ported to .netstandard.

Code Example of such interface:

    [RestContract("http://example.com/api", timeout: 180)]
    public interface IExampleApiClient
    {
        [RestMethod("/v2/login", RestMethod.Post)]
        [Accept("application/x-www-form-urlencoded")]
        [ContenType("application/json")]
        Task<LoginResult> LoginAsync(LoginModel model, [Header("HeaderName")] headerValue);
    }

Later we use helper method to create runtime implementation with necessary DelegatingHandlers and Formatters to serialize and deserialize data based on attributes. In the example above, generated proxy will use https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Net.Http.Formatting/Formatting/JsonMediaTypeFormatter.cs for serializing requests and FormUrlEncodedMediaTypeFormatter for deserializing responses.

In fact there is no changes needed to achieve this, besides adding file link to csproj. I`ve event created pull request for this: #76

This only affects .NetStandard project, as for some reason i cant open .Core version of project in VS, its crashing with NullReferenceException. But same change there would be good.
This pull request adds only FormUrlEncodedMediaTypeFormatter back, but there may be other files that simply left abandoned in new projects.

System.Web.Http - Unhandled use-case with AsyncLocal and Disposing

Problem

In instances of System.Web.Http.ApiController, an AsyncLocal value that is set in the constructor is not preserved through to the Dispose method.

Technical Info

When instances of IHttpController are instantiated, they are instantiated into the ExecutionContext of the System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync method.

Instead of being disposed within SendAsync, the disposal is delayed until System.Web.Http.WebHost.HttpControllerHandler.ProcessRequestAsyncCore (or other similar depending on hosting type) calls System.Net.Http.HttpRequestMessageExtensions.DisposeRequestResources. This disposal is registered by System.Web.Http.ApiController in ExecuteAsync.

Because DisposeRequestResources is called from an ExecutionContext that is not the or a child of the ExecutionContext that the IHttpController was instantiated in, any values stored in an AsyncLocal in the constructor are no longer available in the Dispose method.

Example Code

Below is a trivial implementation that shows the issue.

public class ExampleController 
    : ApiController
{
    private static readonly AsyncLocal<string> _asyncLocal = new AsyncLocal<string>();

    public ExampleController ()
    {
        _asyncLocal.Value = "Test";
    }

    public void Get()
    {
        // _asyncLocal.Value
        // Expected value: "Test"
        // Actual value: "Test"

        // Does not throw, _asyncLocal.Value == "Test"
        if (_asyncLocal.Value != "Test")
            throw new InvalidOperationException();
    }



    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        // _asyncLocal.Value
        // Expected value: "Test"
        // Actual value: null

        // Throws, _asyncLocal.Value == null.
        if (_asyncLocal.Value != "Test")
            throw new InvalidOperationException();
    }
}

Expected Output

No exception occurs

Actual Output

InvalidOperationException thrown by void Dispose(bool disposing).

Use Case

Going outside of the trivial example, one use-case for the desired behavior is when using AsyncLocal values to implicitly flow context into library or otherwise context-unaware code while having that context start at controller instantiation and persisting until controller disposal.

Below is some slightly less trivial code that displays the basics of this use-case:

public class ExampleContext
    : IDisposable
{
    public string ContextValue { get; }

    public static ExampleContext Current
    {
        get => CurrentStack.Peek();
        set => CurrentStack = CurrentStack.Push(value);
    }

    private static IImmutableStack<ExampleContext> CurrentStack
    {
        get => _currentAsyncLocal.Value ?? ImmutableStack<ExampleContext>.Empty;
        set => _currentAsyncLocal.Value = value;
    }

    private static readonly AsyncLocal<IImmutableStack<ExampleContext>> _currentAsyncLocal = new AsyncLocal<IImmutableStack<ExampleContext>>();


    public ExampleContext(string contextValue)
    {
        ContextValue = contextValue;

        Current = this;
    }

    public void Dispose()
    {
        // Throws
        Debug.Assert(!CurrentStack.IsEmpty);
        Debug.Assert(Current == this);

        CurrentStack = CurrentStack.Pop();
    }
}

public class ExampleController
    : ApiController
{
    private readonly ExampleContext _exampleContext;


    public ExampleController()
    {
        _exampleContext = new ExampleContext("Testing");
    }

    public async Task Get()
    {
        // "Testing"
        Debug.WriteLine(_exampleContext.ContextValue);

        // "Testing"
        ExampleLibrary.WriteContextValue();

        // "Testing"
        await ExampleLibrary.WriteContextValueAfterAsync();

        using (new ExampleContext("Nested Context"))
        {
            // "Testing"
            Debug.WriteLine(_exampleContext.ContextValue);

            // "Nested Context"
            ExampleLibrary.WriteContextValue();

            // "Nested Context"
            await ExampleLibrary.WriteContextValueAfterAsync();
        }

        // "Testing"
        Debug.WriteLine(_exampleContext.ContextValue);

        // "Testing"
        ExampleLibrary.WriteContextValue();

        // "Testing"
        await ExampleLibrary.WriteContextValueAfterAsync();
    }



    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        // Throws exception, ExampleContext.Current attempts to Peek() empty stack.
        _exampleContext.Dispose();
    }
}

public static class ExampleLibrary
{
    public static void WriteContextValue()
    {
        Debug.WriteLine(ExampleContext.Current.ContextValue);
    }


    public static async Task WriteContextValueAfterAsync()
    {
        await Task.Yield();

        WriteContextValue();

        await Task.Yield();
    }
}

Discussion Point

Part of this use-case is based on the assumption that IDisposable types should generally be disposed within the same context as when they were instantiated. Is this a correct or expected assumption?

This assumption does hold true for MVC controllers.

Solution

One way to solve this would be to not delay the disposal of IHttpController instances by try-casting it to a disposable and directly disposing it inside System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync after awaitng the HttpResponseMessage.

Work Around

It is possible to delay the instantiation and disposal of the context-specific type until ApiController's ExecuteAsync method by overriding ExecuteAsync and wrapping the awaited base call with the context-specific variable.

Disable tooling build for WSR.Main

Tooling is building in separate branches since 5.2.3 shipped in 2013.

We should just make WSR.Main build runtime DLLs/packages and update the CI accordingly.

We have plans to eventually move all the tooling code into WTE

Port PR: ParameterBinderAttribute race cond

https://aspnetwebstack.codeplex.com/SourceControl/network/forks/jamesgo/ParameterBinderRaceCond/contribution/8790

ParameterBinderAttribute currently has a race condition that can cause ModelBinding to fail and produce a null instance. This can cause reliability dips on service startup due to the model binder returning a null object for our queryParameters model. The time window where this can occur is relatively small, as the race condition only exists while reflecting, but we've observed and successfully repro'd it using our service.

HttpRequestMessageExtensions.CreateResponse<T> should not accept T==HttpStatusCode

In an audit of our code base, we found that there were many calls that looked like:
return Request.CreateResponse(HttpStatusCode.NotFound);
that, due to a refactor, were actually resolving to this:
HttpResponseMessage CreateResponse<T>(this HttpRequestMessage request, T value)
This would make the service return a 200 with a body that says "NotFound". This is clearly not the intent of the programmer.

Possible solutions would be:

  1. Add a more specific extension that specifically targets HttpStatusCode (e.g.System.Net.Http.Formatting has one)
  2. Throw if T is HttpStatusCode

Asp.Net MVC 5 app not working after VS 15.2 update to 15.3

Issue moved from aspnet/Mvc#6666 by @alfeg


After updating VS 15.2 to Vs 15.3 I were blocked with an issue.

Asp.net app suddenly report that it cannot load some assemblies

Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

If I build same project with 15.2 version - everything works perfectly

I've pushed project with repro: https://github.com/alfeg/vs15_3repro

Steps:

  • Build project with VS 15.2.
    -- Ctrl+F5 on REPRO.UI.Headquarters web project.
    -- Should open page with Hello World
  • Build same project with VS 15.3
    -- Ctrl+F5 on REPRO.UI.Headquarters web project.
    -- Could not load file or assembly ... message appear

I've try to change some binding redirects, but has no luck, and this breaks build with 15.2 studio.

Any idea how to resolve, or where I should report this issue?


Html.AntiForgeryToken() adds duplicate X-Frame-Options headers if called more than once

Original bug: https://aspnetwebstack.codeplex.com/workitem/2057


System.Web.WebPages v.3.0.0.0:
Sometimes, more than one anti-forgery token is needed in a page (when there are multiple forms). Calling Html.AntiForgeryToken() causes the "X-Frame-Options: SAMEORIGIN" header to be emitted once per call. In extreme circumstances, this can lead to webserver/proxy malfunctions.


I encountered this issue on a page that uses the Anti-Forgery token within the row for each item in an index view.

The HTTP header was too large and MSIE aborted the connection when the list view was displaying roughly 500 records (selectable view size). Using Fiddler, I noticed the "X-Frame-Options: SAMEORIGIN" header was output for each call to Html.AntiForgeryToken(). The header wasn't output for like this when using Firefox and Chrome. In fact, it only seemed to be output when using MSIE. I was able to change the User Agent in Firefox and Chrome to identify itself as MSIE which reproduced the issue.

I realize there is more than one way to do things, but rather than rewrite the implementation in that view, I came up with a temporary workaround. For each Html.AntiForgeryToken() call made in the list loop. I removed the header eg:

foreach (var item in collection) {
...
    using (Html.BeginForm("Delete", FormMethod.Post, new { id = item.Id }) {
        @Html.AntiForgeryToken()
        // Temporary fix
        Response.Headers.Remove("X-Frame-Options");
    }
...
}

Update to latest tooling

Bring this repo up-to-date w.r.t. the MSBuild version, the StyleCop version, and the Castle.Core / Moq / xUnit versions used in tests. Do not change product code, dependencies, or runtime targets.

This includes a small quirk on the test side: Latest xUnit packages depend on various .NET Standard packages if the test project targets anything earlier than .NET 4.5.2. Update the test projects to target .NET 4.5.2 to avoid those dependencies. We're only testing on more-recent Windows, and therefore desktop .NET, versions anyhow.

See PR aspnet/WebHooks#167 for a smaller variant of this work.

Update to build correctly w/ latest and greatest

The projects in this repository expect Visual Studio 2013 to have been installed on the machine. Even command-line builds fail if this is not the case. Update things enough to build on a system with just Visual Studio 2015 installed.

The Roslyn compiler is slightly stricter in a few cases than previous compilers. Fix these issues as well.

NRE during build in `Microsoft.Web.FxCop.TypeNodeExtensions.GetTaskAssembly()`

Builds are failing every few times, ending with the following:

MSBUILD : error : CA0001 : Rule=Microsoft.Web.FxCop#MW1201, Target=System.Net.Http.UriExtensions.#TryReadQueryAs(System.Uri,System.Type,System.Object&) : Object reference not set to an instance of an object. [C:\dd\AspNetWebStack\src\System.Net.Http.Formatting.NetCore\System.Net.Http.Formatting.NetCore.csproj]
  Code Analysis Complete -- 1 error(s), 0 warning(s)

*** BUILD FAILED ***

bin\CodeAnalysis\NetCore\System.Net.Http.Formatting.dll.CodeAnalysisLog.xml contains additional information:

System.NullReferenceException, Object reference not set to an instance of an object.
   at Microsoft.Web.FxCop.TypeNodeExtensions.GetTaskAssembly(TypeNode type) in C:\dd\AspNetWebStack\tools\src\Microsoft.Web.FxCop\TypeNodeExtensions.cs:line 92
   at Microsoft.Web.FxCop.TypeNodeExtensions.EnsureTaskTypesInitialized(TypeNode type) in C:\dd\AspNetWebStack\tools\src\Microsoft.Web.FxCop\TypeNodeExtensions.cs:line 56
   at Microsoft.Web.FxCop.DoNotCallProblematicMethodsOnTaskRule.VisitMemberBinding(MemberBinding memberBinding) in C:\dd\AspNetWebStack\tools\src\Microsoft.Web.FxCop\DoNotCallProblematicMethodsOnTaskRule.cs:line 39
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.Visit(Node node)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitExpression(Expression expression)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitMethodCall(MethodCall call)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.Visit(Node node)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitExpression(Expression expression)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitExpressionStatement(ExpressionStatement statement)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.Visit(Node node)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitStatements(StatementCollection statements)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitBlock(Block block)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.Visit(Node node)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitStatements(StatementCollection statements)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitBlock(Block block)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitFinally(FinallyNode finallyClause)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitTry(TryNode tryClause)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.Visit(Node node)
   at Microsoft.FxCop.Sdk.BinaryReadOnlyVisitor.VisitStatements(StatementCollection statements)
   at Microsoft.Web.FxCop.DoNotCallProblematicMethodsOnTaskRule.Check(Member member) in C:\dd\AspNetWebStack\tools\src\Microsoft.Web.FxCop\DoNotCallProblematicMethodsOnTaskRule.cs:line 24
   at Microsoft.FxCop.Engines.Introspection.AnalysisVisitor.CheckMember(Member memberToAnalyze, Member member, TargetMember target)

This problem does not occur every build nor every analysis of the PCL (NetCore) System.Net.Http.Formatting.dll assembly. Inconveniently, it never occurs when verbose logging is enabled. And no race is obvious looking at the source.

Correct test failures on Windows 10 machines

The following failures appear specific to Windows 10 machines. At least, failures do not occur on Server 2012 R2 or Windows 8.1 machines -- whether they have VS 2013 or 2015 installed.

  Test Failures:
  System.Web.Helpers.Test.InfoTest.HttpRuntimeInfoReturnsExpectedInfo
  System.Web.Helpers.Test.InfoTest.RenderGeneratesValidXhtml
  System.Web.Helpers.Test.InfoTest.RenderResultContainsExpectedTags
  System.Web.Mvc.Html.Test.TemplateHelpersTest.TemplateHelperFormatsValuesUsingCurrentCulture
  System.Web.WebPages.Test.CultureUtilTest.SetAutoCultureWithInvalidLanguageDoesNothing
  System.Web.WebPages.Test.CultureUtilTest.SetAutoUICultureWithInvalidLanguageDoesNothing

The first 3 failures all relate to HttpRuntime.CodegenDir throwing an NRE when accessed. The next relates to a small change in the date/time formats for the es-PR locale. And the final two failures occur because CultureInfo no longer validates locale names.

Action Selection throws on invalid jQuery query string syntax

A URL like http://example.com/?[&]

Will result in the following exception:

The key is invalid JQuery syntax because it is missing a closing bracket
Parameter name: key","ExceptionType":"System.ArgumentException","StackTrace":"   
   at System.Web.Http.ModelBinding.FormDataCollectionExtensions.NormalizeJQueryToMvc(String key)
   at System.Web.Http.ModelBinding.FormDataCollectionExtensions.<GetJQueryNameValuePairs>d__0.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at System.Net.Http.HttpRequestMessageExtensions.GetQueryNameValuePairs(HttpRequestMessage request)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.GetCandidateActionsWithBindings(HttpControllerContext controllerContext, CandidateAction[] candidatesFound)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.FindMatchingActions(HttpControllerContext controllerContext, Boolean ignoreVerbs)
   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)
   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()

This should result in a 400 (not a 500) or even better, no error at all, as who says you're following the jQuery format anyway

A couple of tests are flakey

See the following occasionally when building this repo locally. Haven't seen either failure on the CI but that rarely builds at all.

C:\dd\AspNetWebStack\tools\WebStack.xunit.targets(13,9): error : System.Web.Http.SelfHost.HttpSelfHostServerTest.SendAsync_ServiceModel_Throws_When_StreamContent_Throws(uri: "/SelfHostServerTest/ThrowBeforeWriteStream", transferMode: Buffered) [FAIL]
        Microsoft.TestCommon.Assert+ThrowsException : Assert.Throws() Failure
        Expected: typeof(System.Net.Http.HttpRequestException)
        Actual:   typeof(System.Threading.Tasks.TaskCanceledException): A task was canceled.
             at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
             at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

and

C:\dd\AspNetWebStack\test\System.Web.Mvc.Test\Test\DataAnnotationsModelValidatorTest.cs(99): error : System.Web.Mvc.Test.DataAnnotationsModelValidatorTest.NoClientRulesByDefault [FAIL] [C:\dd\AspNetWebStack\tools\WebStack.xunit.targets]
        System.InvalidOperationException : Operation is not valid due to the current state of the object.
             at Moq.MethodCall.Execute(ICallContext call)
             at Moq.MethodCallReturn`2.Execute(ICallContext call)
             at Moq.ExecuteCall.HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
             at Moq.Interceptor.Intercept(ICallContext invocation)
             at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
             at Castle.DynamicProxy.AbstractInvocation.Proceed()
             at Castle.Proxies.ModelMetadataProviderProxy.GetMetadataForProperty(Func`1 modelAccessor, Type containerType, String propertyName)
          C:\dd\AspNetWebStack\test\System.Web.Mvc.Test\Test\DataAnnotationsModelValidatorTest.cs(99,0): at System.Web.Mvc.Test.DataAnnotationsModelValidatorTest.NoClientRulesByDefault()

Unhandled exception is being logged when client cancels requests still happens

Original bug: https://aspnetwebstack.codeplex.com/workitem/2283


It appears this issue was clsoed for some reason.
http://aspnetwebstack.codeplex.com/workitem/1797

It still happens on 5.2.3 and I posted details back in April of the error it gives. I get these everyday. (I am not using the workaround listed as this was supposed to be fixed)


I'm getting this too. In my case the Cancellation token is setup within the webapi controller method, and set to cancel after xx seconds. So, the webapi itself if cancelling the request if it's taking too long (we depend on downstream systems so cancel if they are not responding in time), not an external client.

When the cancellation token fires, the webapi call is cancelled but the global exception handler (implementation of IExceptionHandler) is not fired at all. We get a 500 and then an unhandled ASP.NET exception in the Even Log.

WebApi 5.2.3


btw, the workaround listed (DelegatingHandler) doesn't work for me as the cancellation is happening from within the method itself after the delgating handler has been called

MVC5: Asynchronous child actions Not supported

what is the recommended way to execute asynchronous actions (database access) through child actions in MVC5? I understand its very subjective to what i do in the child action. In my case, its only async queries to sql server using EF6.

Is wrapping in a task.run has any side effects in this case or is there any better way microsoft recommends other than changing to Synchronous?

@Html.Action("SampleChildAction)

public PartialViewResult SampleChildAction()
{
    Task.Run(async () => { await asyncMethod(); }).Result; 
    return PartialView("_SampleChildActionView");
}

I couldn't locate anything guidance from microsoft. I would appreciate any help.
https://justsimplycode.com/2016/09/04/child-action-in-mvc-5-does-not-support-async/
dotnet/aspnetcore#343

DefaultBodyModelValidator extensibility

Original PR: https://aspnetwebstack.codeplex.com/SourceControl/network/forks/abatishchev/modelvalidation2/contribution/8644


Opening DefaultBodyModelValidator for changes via inheritance and overriding of its private (now protected virtual) method.

As described in the following issue for Fluent Validation Web API integration package FluentValidation/FluentValidation#178 (comment), FV makes small changes in DFMV but has to copy-paste the whole class as-is because it's barely extendable having all method as private.

This pull request changes them to protected virtual with minimal related changes (few nested private methods should be now protected, one internal interface - public).

Please review!

MPSIT Engineering extensively uses ASP.NET Web API for current and new projects, and relies on Fluent Validation to validate input. But unfortunately we're unable to change some of the behaviors without copy-pasting huge pieces of code, what would be perfectly avoidable with the proposed change.

Thanks,
Alex

Get tests working in Visual Studio

Since the last time we did anything w/ this code, xUnit has removed the Visual Studio extension and moved to a new NuGet package for the same purpose (xunit.runner.visualstudio). Get the code using this new approach.

Also move from xUnit 1.9.1 to the current stable version (2.1.0). This likely involves removing references to the deprecated xunit.extensions package.

Potential serialization issues for saved type information

Recent FxCop versions detect the following issues:

 System.Web.Http.SelfHost -> C:\dd\AspNetWebStack\bin\CodeAnalysis\System.Web.Http.SelfHost.dll
 Running Code Analysis...
C:\dd\AspNetWebStack\src\System.Web.Http.WebHost\HttpControllerTypeCacheSerializer.cs(103): error CA1305: Microsoft.Globalization : Because the behavior of 'DateTime.ToString()' could vary based on the current user's locale settings, replace this call in 'HttpControllerTypeCacheSerializer.SerializeTypes(IEnumerable<Type>, TextWriter)' with a call to 'DateTime.ToString(IFormatProvider)'. If the result of 'DateTime.ToString(IFormatProvider)' will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. [C:\dd\AspNetWebStack\src\System.Web.Http.WebHost\System.Web.Http.WebHost.csproj]
 Code Analysis Complete -- 1 error(s), 0 warning(s)

and

 System.Web.Mvc -> C:\dd\AspNetWebStack\bin\CodeAnalysis\System.Web.Mvc.dll
 Running Code Analysis...
C:\dd\AspNetWebStack\src\System.Web.Mvc\TypeCacheSerializer.cs(98): error CA1305: Microsoft.Globalization : Because the behavior of 'DateTime.ToString()' could vary based on the current user's locale settings, replace this call in 'TypeCacheSerializer.SerializeTypes(IEnumerable<Type>, TextWriter)' with a call to 'DateTime.ToString(IFormatProvider)'. If the result of 'DateTime.ToString(IFormatProvider)' will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider' parameter. Otherwise, if the result will be stored and accessed by software, such as when it is persisted to disk or to a database, specify 'CultureInfo.InvariantCulture'. [C:\dd\AspNetWebStack\src\System.Web.Mvc\System.Web.Mvc.csproj]
 Code Analysis Complete -- 1 error(s), 0 warning(s)

This is a correctness issue and it breaks our builds. But it turns this is not a functional problem since the affected attribute in the saved XML is ignored when the info is read back. (I incorrectly thought it was a functional issue in PR #15 discussions.)

Recommend fixing the problem rather than suppressing it. Has an easy fix and suppressions are ugly.

ApiDescription.ResponseDescription is not initialized

When creating an ApiDescription from it's own ctor the ResponseDescription is not initiated and the set-property is internal.

public ResponseDescription ResponseDescription { get; internal set; }

Workaround

var apiDescriptor = new ApiDescriptor();
typeof(ApiDescription).GetProperty(nameof(ApiDescription.ResponseDescription)).SetValue(apiDescriptor, new ResponseDescription());

ASP.NET MVC AntiforgeryToken missing issue

From @kyajiv on September 10, 2016 12:40

AntiforgeryToken doesn't work if user browse the website using googleweblight.

System.Web.Mvc.HttpAntiForgeryException (0x80004005): The required anti-forgery form field "__RequestVerificationToken" is not present.
at System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken)
at System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase httpContext)
at System.Web.Helpers.AntiForgery.Validate()
at System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext)
at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)

Copied from original issue: aspnet/Mvc#5263

Fix `System.Web.Http.ApiControllerTest.Setting_CustomActionSelector` test failure

This test currently fails consistently with the following stack trace

    System.Web.Http.ApiControllerTest.Setting_CustomActionSelector [FAIL]
      System.NullReferenceException : Object reference not set to an instance of an object.
      Stack Trace:
           at lambda_method(Closure , Object , Object[] )
        src\System.Web.Http\Controllers\ReflectedHttpActionDescriptor.cs(453,0): at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.<GetExecutor>b__3(Object instance, Object[] methodParameters)
        src\System.Web.Http\Controllers\ReflectedHttpActionDescriptor.cs(150,0): at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
        --- End of stack trace from previous location where exception was thrown ---
           at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
           at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        src\System.Web.Http\Controllers\ApiControllerActionInvoker.cs(34,0): at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()
        --- End of stack trace from previous location where exception was thrown ---
           at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
           at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
        src\System.Web.Http\Controllers\ActionFilterResult.cs(42,0): at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()

16 test failures related to `JObject` instances cast to `dynamic`

Test failures do not occur on all machines. But, they happen consistently on machines with .NET 4.7 installed. All failures involve unexpected RuntimeBinderExceptions. And, those Exceptions are thrown in consistent locations:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'oauth_token'
    at CallSite.Target(Closure , CallSite , Object )
    ...

The error messages mention oauth_token in two cases (in Microsoft.AspNet.Facebook.Test.FacebookContextModelBinderTest) and ExceptionType in the remaining 14 failures (2 in System.Web.Http.ExceptionHandlingTest and 12 in System.Web.Http.IncludeErrorDetailTest).

Could workaround the ExceptionType failures, using something other than dynamic in the test code. However the FacebookClient's ParseSignedRequest(...) method internally casts a JObject instance to dynamic. (Unclear why e.g. FacebookAuthorizeFilterHookTest tests succeed while FacebookContextModelBinderTest tests fail.)

Run tests against latest versions of our dependencies

All product code has outdated dependencies e.g. Newtonsoft.Json v6.0.4. Should test to see if tests run even when using the latest and greatest e.g. Newtonsoft.Json v9.0.1.

This issue is not about the major breaking changes involved in updating our product dependencies. Likely choices are either to perform a one-time confirmation that our tests work fine or to (somehow) automate testing against both the minimum required versions and the latest.

WebApi skips ExceptionLogger on TaskCanceledException even if it's not associated with the request's CancellationToken

It makes sense that you skip invoking ExceptionLoggers when the client cancels a request. However, TaskCanceledExceptions can sometimes be thrown that were not due to the client cancelling a request. Ignoring these cases can cause crucial exception information to be lost and unlogged.

Ideally, you should be able to check whether the CancellationToken on the TaskCanceledException is the same as the one passed into the controller action, and only skip logging if it is. Or, alternatively, you could at least check to see whether the token associated with the request had cancellation requested (via IsCancellationRequested). But please don't just ignore all TaskCanceledExceptions indiscriminately.

Update to build correctly w/ latest and greatest

The projects in this repository expect Visual Studio 2013 to have been installed on the machine. Even command-line builds fail if this is not the case. Update things enough to build on a system with just Visual Studio 2015 installed.

The Roslyn compiler is slightly stricter in a few cases than previous compilers. Fix these issues as well.

Fix loc build

Not sure localized builds of the template projects are working on the CI. Certainly, Web Stack Runtime / Main.Signed.AllLanguages builds succeed only because lsbuild.exe errors like the following are ignored:

Task "Exec"
  SET RazorLocParserBuildDirectory=C:\WSR\Tooling\bin\Release\&C:\WSR\Tooling\tools\loc\lsbuild.exe response C:\WSR\Tooling\obj\Release\loc\xo3cgpzm.zdnBatch.response
  Microsoft Localization Studio Build Tools Version 6.11.2218.0 (6.0.0.0)
  LocStudio Build Tool
  Copyright (c) Microsoft Corporation. All rights reserved.

  LSBuild : > Starting 'parse /p 305 /l en-US  /s C:\WSR\Tooling\tools\loc\default.lss  /s C:\WSR\Tooling\tools\loc\CommentAndUI_SourceEncoding.lss /o C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lcg /c C:\WSR\Tooling\localize\comments\templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lci C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild :   > Parsing File 'C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild :     Error BL1024 - RazorLocParser.dll - C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml(7:0,7): The 'model' keyword must be followed by a type name on the same line.
  LSBuild :     > LSBuild-Parse
  LSBuild :     < Done.
  LSBuild :     > Processing Comments
  LSBuild :       > Processing Commenting file 'C:\WSR\Tooling\localize\comments\templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lci'
  LSBuild :       < Done
  LSBuild :     < Done
  LSBuild :     > Validating Resources
  LSBuild :     < Done
  LSBuild :   < Done
  LSBuild : < The command completed successfully. Elapsed time 0.4843692 seconds
  LSBuild : > Starting 'generate /p 305 /d fr-FR /iu   /s C:\WSR\Tooling\tools\loc\default.lss  /s C:\WSR\Tooling\tools\loc\CommentAndUI_SourceEncoding.lss /c C:\WSR\Tooling\localize\comments\templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lci /ol C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lcx /t C:\WSR\Tooling\localize\FRA\templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lcl /o C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild :   > Generating 'C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild :     > Generating File 'C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild :       > Parsing File 'C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild :         Error BL1024 - RazorLocParser.dll - C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml(7:0,7): The 'model' keyword must be followed by a type name on the same line.
  LSBuild :         > LSBuild-Parse
  LSBuild :         < Done.
  LSBuild :         > Processing Comments
  LSBuild :           > Processing Commenting file 'C:\WSR\Tooling\localize\comments\templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lci'
  LSBuild :           < Done
  LSBuild :         < Done
  LSBuild :       < Done
  LSBuild :       > Updating Translation File 'C:\WSR\Tooling\localize\FRA\templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lcl'
  LSBuild :       < Done
  LSBuild :       Error BL1024 - RazorLocParser.dll - C:\WSR\Tooling\obj\Release\OneMvcTemplates\TemplateSource\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml(7:0,7): The 'model' keyword must be followed by a type name on the same line.
  LSBuild :       > LSBuild-Generate
  LSBuild :       < Done.
  LSBuild :     < Done
  LSBuild :     > Saving translation file 'C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml.lcx'
  LSBuild :     < Done
  LSBuild :   < Generate failed : 'C:\WSR\Tooling\bin\Release\FRA\src\Templates\OneMvc\Templates\MvcBasicApplication\_OrgAuth\_Read\Views\Home\UserProfile.cshtml'
  LSBuild : < The command completed successfully. Elapsed time 0.641679 seconds

C:\WSR\Tooling\Loc.proj(3130,9): warning MSB3073: The command "SET RazorLocParserBuildDirectory=C:\WSR\Tooling\bin\Release\&C:\WSR\Tooling\tools\loc\lsbuild.exe response C:\WSR\Tooling\obj\Release\loc\xo3cgpzm.zdnBatch.response" exited with code 1.
  The previous error was converted to a warning because the task was called with ContinueOnError=true.
  Build continuing because "ContinueOnError" on the task "Exec" is set to "true".
Done executing task "Exec" -- FAILED.

FYI the above errors occur because the @model directives contain $safeprojectname$ in the type names. Probably need to substitute another token before calling the Razor parser and restore $safeprojectname$ after.

And the response files aren't 💯% correct:

  LSBuild : > Starting 'parse /l en-US  /s C:\WSR\Tooling\tools\loc\default.lss  /s C:\WSR\Tooling\tools\loc\locxml_WPT_nuspec.lss /o C:\WSR\Tooling\bin\Release\FRA\src\packages\LocalizationPackages\Microsoft.AspNet.Facebook\Microsoft.AspNet.Facebook.nuspec.lcg /c C:\WSR\Tooling\localize\comments\packages\Microsoft.AspNet.Facebook.nuspec.lci C:\WSR\Tooling\src\packages\LocalizationPackages\Microsoft.AspNet.Cors\Microsoft.AspNet.Facebook.nuspec'
  LSBuild :   Error CD0002 - The command threw an exception - File 'C:\WSR\Tooling\src\packages\LocalizationPackages\Microsoft.AspNet.Cors\Microsoft.AspNet.Facebook.nuspec' not found
  LSBuild : < The command failed.  Elapsed time 0 seconds
  LSBuild : > Starting 'generate /d fr-FR /iu   /s C:\WSR\Tooling\tools\loc\default.lss  /s C:\WSR\Tooling\tools\loc\locxml_WPT_nuspec.lss /c C:\WSR\Tooling\localize\comments\packages\Microsoft.AspNet.Facebook.nuspec.lci /ol C:\WSR\Tooling\bin\Release\FRA\src\packages\LocalizationPackages\Microsoft.AspNet.Facebook\Microsoft.AspNet.Facebook.nuspec.lcx /t C:\WSR\Tooling\localize\FRA\packages\LocalizationPackages\Microsoft.AspNet.Facebook.nuspec.lcl /o C:\WSR\Tooling\bin\Release\FRA\src\packages\LocalizationPackages\Microsoft.AspNet.Facebook\Microsoft.AspNet.Facebook.nuspec C:\WSR\Tooling\src\packages\LocalizationPackages\Microsoft.AspNet.Cors\Microsoft.AspNet.Facebook.nuspec'
  LSBuild :   > Generating 'C:\WSR\Tooling\bin\Release\FRA\src\packages\LocalizationPackages\Microsoft.AspNet.Facebook\Microsoft.AspNet.Facebook.nuspec'
  LSBuild :   < Generate failed : 'C:\WSR\Tooling\bin\Release\FRA\src\packages\LocalizationPackages\Microsoft.AspNet.Facebook\Microsoft.AspNet.Facebook.nuspec'
  LSBuild :   Error CD0002 - The command threw an exception - File 'C:\WSR\Tooling\src\packages\LocalizationPackages\Microsoft.AspNet.Cors\Microsoft.AspNet.Facebook.nuspec' not found
  LSBuild : < The command failed.  Elapsed time 0 seconds

Separately, Microsoft.AspNet.WebApi.Client.fr packages are available on http://www.nuget.org but not in our nightly CI feed on http://www.myget.org. This is more likely about nightly build configuration than anything else because the packages are created and signed in the CI builds. But is that configuration correct?

Update readme.md to explain which versions correspond to which tags

See original discussion here: https://aspnetwebstack.codeplex.com/discussions/657260

Unfortunately there's probably not good docs on it right now (that I'm aware of). The problem is that the repo contains several different projects: MVC, Web API, Razor, and Web Pages. Each one has its own version (they came out at different times). So because of that, there isn't one simple version tag that we can use.

We're looking to clean some stuff up in this repo, so I'll make a note to add some doc/wiki entry that explains the tags/branches in the repo.

Support for params keyword

I was surprised to see that params was not supported by Web API actions.

[HttpPost]
[Route("ParamsTest")]
public String[] Test([FromBody] params String[] values)
{
    return values;
}

Test 1

POST / HTTP/1.1
["a","b","c"]

The above request responds with:

["a","b","c"]

Test 2

POST / HTTP/1.1
"a"

The above request responds with:

null

However, I expected:

["a"]

Conclusion

It would be great if the binder could respect the params modifier, thus enabling endpoints to accept one-or-many of a given parameter.

For the sake of completeness, passing around non-primitive objects:

[HttpPost]
[Route("Customers")]
public void Test([FromBody] params Customer[] customers)
{
    // do important stuff
}

Would accept:

POST / HTTP/1.1
{"Name":"Alice"}

And as well, it would accept:

POST / HTTP/1.1
[{"Name":"Alice"},{"Name":"Bob"},{"Name":"Carol"}]

MediaTypeFormatter in the request CultureInfo

Hi guys,

I have registered custom JsonConverters in the default SerializerSettings of the JsonFormatter, but one of them requires to send the result of evaluating ToString in the request CultureInfo.

Unfortunately at some of the async jumps in the request pipeline (I suppose) the culture gets set back to en-US. The JsonSerializer´s Culture on the other side uses Invariant Culture.

I've tried writing my own MediaTypeFormatter but, while the request Culture is present in CanWriteType, by the time WriteToStreamAsync is called the Culture is set back to en-US.

Just to note, I'm setting the culture in my own IAuthorizationFilter in the method ExecuteAuthorizationFilterAsync just before calling continuation().

Is there any way to run MediaFormatters in the request culture? I'm considering moving to .Net Core. Could this problem have an easier solution there?

Thanks a lot

Move to newer xunit.analyzers package

The current xunit.analyzers package (v0.7.0) is not a stable version, contains a few bugs, and we have workarounds in our test code for some of those bugs. Nothing newer is available. But, when the package is updated…

Relevant bugs and the workarounds we could remove after moving to new analyzer package:

  • xunit/xunit#1466, xunit.analyzer raises false positive warnings on "public static" and "public abstract" methods
    • remove xUnit1013 suppression in MediaTypeFormatterTestBase<TFormatter>
  • xunit/xunit#1502, InvalidCastException thrown in AssertEqualShouldNotBeUsedForCollectionSizeCheck
    • change 'b' - '\0' expressions in LookaheadTextReaderTestBase back to just 'b'
  • xunit/xunit#1505, Avoid AssertEqualShouldNotBeUsedForBoolLiteralCheck false positives
    • remove casts of literal expressions on LHS of an Assert.Equal(...) e.g. change Assert.Equal((object)true, ex.Data["WebPages.VersionChange"]); back to Assert.Equal(true, ex.Data["WebPages.VersionChange"]);

Add Html.Action method with route name parameter

Hello team,

I found that Html.Action(string actionName, string controllerName) is very slow if routings collection is huge (in my case around 1000 items). Most of the time it spend in finding route with checking every single route.

It would would be great to have Html.Action method which will take routeName as a parameter. It will allow to use RouteCollection.GetVirtualPathForArea(requestContext, routeName, routeValues) method, which is actually just dictionary lookup internally.

I created implementation in my local project codebase by copy pasting some code pieces from MVC, because Html.Action method implementation relies on some internal classes, so it cannot be properly implemented from outside of MVC. And this implementation is much more faster.

Use smaller test collections

The fix for #41 was intended to be temporary. It worked but had the cost of placing a large number of tests in the same collection, preventing parallel execution of the affected test classes.

Should revert f098836 and instead use [CollectionDefinition(DisableParallelization = true)] for either the original collection or a new collection containing DisplayExtensionsTest, EditorExtensionsTest and any other test class that writes to the ScopeStorage, ViewEngines.Engines or ModelMetadataProviders.Current static properties.

FYI:

  • DisableParallelization is a new feature of the xUnit 2.3.0 runtime. It ensures no other test collection (aka test class in most cases) runs in parallel with one using that CollectionDefinition.
  • f098836 affected only the System.Web.Mvc.Test test assembly but should check the other assemblies to see if DisableParallelization would help there too i.e. see if only a small subset of the test collections change static properties
  • no test assembly has more than one explicit test collection i.e. almost every test class runs in parallel with others
  • multiple test assemblies declare a "Uses ScopeStorage or ViewEngines.Engines" test collection but, due to the assembly boundaries, they aren't really the same

Support for mixed-mode authentication

Hi. We're building an ASP.NET MVC 5 app in Visual Studio and have used the great library OWIN-MixedAuth to add mixed-mode authentication: to allow both Windows and Forms auth in one app. This way our intranet and external users can use the same app, being authenticated against the Identity Library and its associated tables on SQL Server.

We'd like to request the addition of this library to future versions of MVC/MVC Core. We've found it to be solid with great support. And many enterprises need mixed authentication. This solution is solid and secure.

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.