Move JSON.NET specific features to a separate assembly

This commit is contained in:
Pranav K 2018-12-17 07:32:15 +05:30
parent d116ab8550
commit cdc66c5f98
170 changed files with 1457 additions and 2147 deletions

View File

@ -136,9 +136,9 @@ This can be done once #4246 is complete, and done in conjunction with converting
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.Core" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.Cors" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.DataAnnotations" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.Localization" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Category="ship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.Razor" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.RazorPages" Category="noship" />
<PackageArtifact Include="Microsoft.AspNetCore.Mvc.TagHelpers" Category="noship" />

View File

@ -99,9 +99,9 @@
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Core" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.Core\Microsoft.AspNetCore.Mvc.Core.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Cors" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.Cors\Microsoft.AspNetCore.Mvc.Cors.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.DataAnnotations" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.DataAnnotations\Microsoft.AspNetCore.Mvc.DataAnnotations.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Formatters.Json" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.Formatters.Json\Microsoft.AspNetCore.Mvc.Formatters.Json.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.Formatters.Xml\Microsoft.AspNetCore.Mvc.Formatters.Xml.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Localization" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.Localization\Microsoft.AspNetCore.Mvc.Localization.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.NewtonsoftJson\Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.RazorPages" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.RazorPages\Microsoft.AspNetCore.Mvc.RazorPages.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.Razor" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.Razor\Microsoft.AspNetCore.Mvc.Razor.csproj" />
<ProjectReferenceProvider Include="Microsoft.AspNetCore.Mvc.TagHelpers" ProjectPath="$(RepositoryRoot)src\Mvc\src\Microsoft.AspNetCore.Mvc.TagHelpers\Microsoft.AspNetCore.Mvc.TagHelpers.csproj" />

View File

@ -54,7 +54,6 @@
<Dependency Include="Microsoft.AspNetCore.Mvc.Core" Version="$(MicrosoftAspNetCoreMvcCorePackageVersion)" />
<Dependency Include="Microsoft.AspNetCore.Mvc.Cors" Version="$(MicrosoftAspNetCoreMvcCorsPackageVersion)" />
<Dependency Include="Microsoft.AspNetCore.Mvc.DataAnnotations" Version="$(MicrosoftAspNetCoreMvcDataAnnotationsPackageVersion)" />
<Dependency Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="$(MicrosoftAspNetCoreMvcFormattersJsonPackageVersion)" />
<Dependency Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="$(MicrosoftAspNetCoreMvcFormattersXmlPackageVersion)" />
<Dependency Include="Microsoft.AspNetCore.Mvc.Localization" Version="$(MicrosoftAspNetCoreMvcLocalizationPackageVersion)" />
<Dependency Include="Microsoft.AspNetCore.Mvc.Razor" Version="$(MicrosoftAspNetCoreMvcRazorPackageVersion)" />

View File

@ -1,3 +1,3 @@
@ECHO OFF
SET RepoRoot=%~dp0..\..
%RepoRoot%\build.cmd -LockFile %RepoRoot%\korebuild-lock.txt -projects %~dp0**\*.*proj %*
%RepoRoot%\build.cmd -projects %~dp0\**\*.*proj %*

View File

@ -25,6 +25,7 @@
<Reference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
<Reference Include="Microsoft.AspNetCore.Identity.UI" />
<Reference Include="Microsoft.AspNetCore.Mvc" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<Reference Include="Microsoft.AspNetCore.Rewrite" />
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" />
<Reference Include="Microsoft.AspNetCore.Server.Kestrel" />

View File

@ -34,7 +34,8 @@ namespace Identity.DefaultUI.WebSite
{
options.Conventions.AuthorizeFolder("/Areas/Identity/Pages/Account/Manage");
options.Conventions.AuthorizePage("/Areas/Identity/Pages/Account/Logout");
});
})
.AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

View File

@ -31,7 +31,8 @@ namespace Identity.DefaultUI.WebSite
.AddUserManager<UserManager<Microsoft.AspNetCore.Identity.Test.PocoUser>>();
services.AddSingleton<IUserStore<Microsoft.AspNetCore.Identity.Test.PocoUser>, InMemoryUserStore<Microsoft.AspNetCore.Identity.Test.PocoUser>>();
services.AddMvc();
services.AddMvc()
.AddNewtonsoftJson();
}
}
}

View File

@ -12,7 +12,7 @@ using Microsoft.Extensions.FileProviders;
namespace Identity.DefaultUI.WebSite
{
public class StartupBase<TUser,TContext>
public class StartupBase<TUser,TContext>
where TUser : class
where TContext : DbContext
{
@ -45,7 +45,8 @@ namespace Identity.DefaultUI.WebSite
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<TContext>();
services.AddMvc();
services.AddMvc()
.AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

View File

@ -2,8 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
"System": "Warning",
"Microsoft": "Warning"
}
}
}

View File

@ -83,11 +83,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Ab
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.ViewFeatures", "src\Microsoft.AspNetCore.Mvc.ViewFeatures\Microsoft.AspNetCore.Mvc.ViewFeatures.csproj", "{3F8B8FC1-9FE4-4788-8991-367113E8D7AD}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Formatters.Json", "src\Microsoft.AspNetCore.Mvc.Formatters.Json\Microsoft.AspNetCore.Mvc.Formatters.Json.csproj", "{3FC8D9D6-9352-43A3-8E81-422F270085B7}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.NewtonsoftJson", "src\Microsoft.AspNetCore.Mvc.NewtonsoftJson\Microsoft.AspNetCore.Mvc.NewtonsoftJson.csproj", "{3FC8D9D6-9352-43A3-8E81-422F270085B7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Formatters.Xml", "src\Microsoft.AspNetCore.Mvc.Formatters.Xml\Microsoft.AspNetCore.Mvc.Formatters.Xml.csproj", "{42C81540-CD47-4C68-A7A3-2A93B9C3B210}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Formatters.Json.Test", "test\Microsoft.AspNetCore.Mvc.Formatters.Json.Test\Microsoft.AspNetCore.Mvc.Formatters.Json.Test.csproj", "{493780DA-E696-40FF-BD12-4A5C5736F292}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.NewtonsoftJson.Test", "test\Microsoft.AspNetCore.Mvc.NewtonsoftJson.Test\Microsoft.AspNetCore.Mvc.NewtonsoftJson.Test.csproj", "{493780DA-E696-40FF-BD12-4A5C5736F292}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.AspNetCore.Mvc.Formatters.Xml.Test", "test\Microsoft.AspNetCore.Mvc.Formatters.Xml.Test\Microsoft.AspNetCore.Mvc.Formatters.Xml.Test.csproj", "{22019146-BDFA-442E-8C8E-345FB9644578}"
EndProject

View File

@ -24,7 +24,7 @@
<Reference Include="Microsoft.AspNetCore.Authentication" />
<Reference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
<Reference Include="Microsoft.AspNetCore.Mvc.DataAnnotations" />
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<Reference Include="Microsoft.AspNetCore.Server.Kestrel" />
<Reference Include="Microsoft.Extensions.Configuration.CommandLine" />
</ItemGroup>

View File

@ -125,7 +125,7 @@ namespace BasicApi
services
.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters(json => json.ContractResolver = new CamelCasePropertyNamesContractResolver())
.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver())
.AddDataAnnotations();
}

View File

@ -4,8 +4,6 @@
<TargetFramework>netcoreapp3.0</TargetFramework>
<!-- Workaround https://github.com/dotnet/core-setup/issues/3726 -->
<GenerateDependencyFile>false</GenerateDependencyFile>
<_EnableAllInclusiveRazorSdk>true</_EnableAllInclusiveRazorSdk>
<IsBenchmarkProject>true</IsBenchmarkProject>
</PropertyGroup>

View File

@ -1,15 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<RazorCompileOnBuild>true</RazorCompileOnBuild>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<Reference Include="Microsoft.AspNetCore.Diagnostics" />
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" />
<Reference Include="Microsoft.AspNetCore.Server.Kestrel" />

View File

@ -8,7 +8,6 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Core, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Cors, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Json, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Xml, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Localization, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Razor, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
@ -23,7 +22,6 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Core.TestCommon, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Cors.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.DataAnnotations.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Json.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Xml.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Localization.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]

View File

@ -24,9 +24,9 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationParts
"Microsoft.AspNetCore.Mvc.Core",
"Microsoft.AspNetCore.Mvc.Cors",
"Microsoft.AspNetCore.Mvc.DataAnnotations",
"Microsoft.AspNetCore.Mvc.Formatters.Json",
"Microsoft.AspNetCore.Mvc.Formatters.Xml",
"Microsoft.AspNetCore.Mvc.Localization",
"Microsoft.AspNetCore.Mvc.NewtonsoftJson",
"Microsoft.AspNetCore.Mvc.Razor",
"Microsoft.AspNetCore.Mvc.RazorPages",
"Microsoft.AspNetCore.Mvc.TagHelpers",

View File

@ -3,10 +3,9 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc
{
@ -28,9 +27,8 @@ namespace Microsoft.AspNetCore.Mvc
/// Creates a new <see cref="JsonResult"/> with the given <paramref name="value"/>.
/// </summary>
/// <param name="value">The value to format as JSON.</param>
/// <param name="serializerSettings">The <see cref="JsonSerializerSettings"/> to be used by
/// the formatter.</param>
public JsonResult(object value, JsonSerializerSettings serializerSettings)
/// <param name="serializerSettings">The serializer settings to be used by the formatter.</param>
public JsonResult(object value, object serializerSettings)
{
if (serializerSettings == null)
{
@ -47,9 +45,9 @@ namespace Microsoft.AspNetCore.Mvc
public string ContentType { get; set; }
/// <summary>
/// Gets or sets the <see cref="JsonSerializerSettings"/>.
/// Gets or sets the serializer settings.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; }
public object SerializerSettings { get; set; }
/// <summary>
/// Gets or sets the HTTP status code.
@ -70,7 +68,17 @@ namespace Microsoft.AspNetCore.Mvc
}
var services = context.HttpContext.RequestServices;
var executor = services.GetRequiredService<JsonResultExecutor>();
var executor = services.GetService<IActionResultExecutor<JsonResult>>();
if (executor == null)
{
throw new InvalidOperationException(Resources.FormatReferenceToNewtonsoftJsonRequired(
$"{nameof(JsonResult)}.{nameof(ExecuteResultAsync)}",
"Microsoft.AspNetCore.Mvc.NewtonsoftJson",
nameof(IMvcBuilder),
"AddNewtonsoftJson",
"ConfigureServices(...)"));
}
return executor.ExecuteAsync(context, this);
}
}

View File

@ -3,7 +3,6 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc
{
@ -18,7 +17,6 @@ namespace Microsoft.AspNetCore.Mvc
/// (e.g., using HTML [W3C.REC-html5-20141028]). When this member is not present, its value is assumed to be
/// "about:blank".
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "type")]
public string Type { get; set; }
/// <summary>
@ -26,25 +24,21 @@ namespace Microsoft.AspNetCore.Mvc
/// of the problem, except for purposes of localization(e.g., using proactive content negotiation;
/// see[RFC7231], Section 3.4).
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "title")]
public string Title { get; set; }
/// <summary>
/// The HTTP status code([RFC7231], Section 6) generated by the origin server for this occurrence of the problem.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "status")]
public int? Status { get; set; }
/// <summary>
/// A human-readable explanation specific to this occurrence of the problem.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "detail")]
public string Detail { get; set; }
/// <summary>
/// A URI reference that identifies the specific occurrence of the problem.It may or may not yield further information if dereferenced.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "instance")]
public string Instance { get; set; }
/// <summary>
@ -58,7 +52,6 @@ namespace Microsoft.AspNetCore.Mvc
/// The round-tripping behavior for <see cref="Extensions"/> is determined by the implementation of the Input \ Output formatters.
/// In particular, complex types or collection types may not round-trip to the original type when using the built-in JSON or XML formatters.
/// </remarks>
[JsonExtensionData]
public IDictionary<string, object> Extensions { get; } = new Dictionary<string, object>(StringComparer.Ordinal);
}
}

View File

@ -10,7 +10,6 @@ using Microsoft.AspNetCore.Mvc.Formatters;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.ApiExplorer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Cors, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Json, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Xml, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Localization, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Razor, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
@ -25,7 +24,6 @@ using Microsoft.AspNetCore.Mvc.Formatters;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Core.TestCommon, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Cors.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.DataAnnotations.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Json.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Xml.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Localization.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]

View File

@ -1690,6 +1690,20 @@ namespace Microsoft.AspNetCore.Mvc.Core
internal static string FormatApiConventions_Title_422()
=> GetString("ApiConventions_Title_422");
/// <summary>
/// '{0}' requires a reference to '{1}'. Configure your application by adding a reference to the '{1}' package and calling '{2}.{3}' inside the call to '{4}' in the application startup code.
/// </summary>
internal static string ReferenceToNewtonsoftJsonRequired
{
get => GetString("ReferenceToNewtonsoftJsonRequired");
}
/// <summary>
/// '{0}' requires a reference to '{1}'. Configure your application by adding a reference to the '{1}' package and calling '{2}.{3}' inside the call to '{4}' in the application startup code.
/// </summary>
internal static string FormatReferenceToNewtonsoftJsonRequired(object p0, object p1, object p2, object p3, object p4)
=> string.Format(CultureInfo.CurrentCulture, GetString("ReferenceToNewtonsoftJsonRequired"), p0, p1, p2, p3, p4);
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);

View File

@ -490,4 +490,7 @@
<data name="ApiConventions_Title_422" xml:space="preserve">
<value>Unprocessable Entity</value>
</data>
<data name="ReferenceToNewtonsoftJsonRequired" xml:space="preserve">
<value>'{0}' requires a reference to '{1}'. Configure your application by adding a reference to the '{1}' package and calling '{2}.{3}' inside the call to '{4}' in the application startup code.</value>
</data>
</root>

View File

@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc
{
@ -84,7 +83,6 @@ namespace Microsoft.AspNetCore.Mvc
/// <summary>
/// Gets the validation errors associated with this instance of <see cref="ValidationProblemDetails"/>.
/// </summary>
[JsonProperty(PropertyName = "errors")]
public IDictionary<string, string[]> Errors { get; } = new Dictionary<string, string[]>(StringComparer.Ordinal);
}
}

View File

@ -1,37 +0,0 @@
// 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 Microsoft.AspNetCore.Mvc;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extensions methods for configuring MVC via an <see cref="IMvcBuilder"/>.
/// </summary>
public static class MvcJsonMvcBuilderExtensions
{
/// <summary>
/// Adds configuration of <see cref="MvcJsonOptions"/> for the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">The <see cref="MvcJsonOptions"/> which need to be configured.</param>
public static IMvcBuilder AddJsonOptions(
this IMvcBuilder builder,
Action<MvcJsonOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure(setupAction);
return builder;
}
}
}

View File

@ -1,85 +0,0 @@
// 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 Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Formatters.Json;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace Microsoft.Extensions.DependencyInjection
{
public static class MvcJsonMvcCoreBuilderExtensions
{
public static IMvcCoreBuilder AddJsonFormatters(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddJsonFormatterServices(builder.Services);
return builder;
}
public static IMvcCoreBuilder AddJsonFormatters(
this IMvcCoreBuilder builder,
Action<JsonSerializerSettings> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
AddJsonFormatterServices(builder.Services);
builder.Services.Configure<MvcJsonOptions>((options) => setupAction(options.SerializerSettings));
return builder;
}
/// <summary>
/// Adds configuration of <see cref="MvcJsonOptions"/> for the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
/// <param name="setupAction">The <see cref="MvcJsonOptions"/> which need to be configured.</param>
/// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
public static IMvcCoreBuilder AddJsonOptions(
this IMvcCoreBuilder builder,
Action<MvcJsonOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
builder.Services.Configure(setupAction);
return builder;
}
// Internal for testing.
internal static void AddJsonFormatterServices(IServiceCollection services)
{
services.TryAddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, MvcJsonMvcOptionsSetup>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IApiDescriptionProvider, JsonPatchOperationsArrayProvider>());
services.TryAddSingleton<JsonResultExecutor>();
}
}
}

View File

@ -1,58 +0,0 @@
// <auto-generated />
namespace Microsoft.AspNetCore.Mvc.Formatters.Json
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNetCore.Mvc.Formatters.Json.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// {0} cannot be null.
/// </summary>
internal static string ContractResolverCannotBeNull
{
get => GetString("ContractResolverCannotBeNull");
}
/// <summary>
/// {0} cannot be null.
/// </summary>
internal static string FormatContractResolverCannotBeNull(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("ContractResolverCannotBeNull"), p0);
/// <summary>
/// Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.
/// </summary>
internal static string InvalidContractResolverForJsonCasingConfiguration
{
get => GetString("InvalidContractResolverForJsonCasingConfiguration");
}
/// <summary>
/// Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.
/// </summary>
internal static string FormatInvalidContractResolverForJsonCasingConfiguration(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("InvalidContractResolverForJsonCasingConfiguration"), p0, p1);
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -1,910 +0,0 @@
{
"AssemblyIdentity": "Microsoft.AspNetCore.Mvc.Formatters.Json, Version=2.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60",
"Types": [
{
"Name": "Microsoft.AspNetCore.Mvc.JsonPatchExtensions",
"Visibility": "Public",
"Kind": "Class",
"Abstract": true,
"Static": true,
"Sealed": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "ApplyTo<T0>",
"Parameters": [
{
"Name": "patchDoc",
"Type": "Microsoft.AspNetCore.JsonPatch.JsonPatchDocument<T0>"
},
{
"Name": "objectToApplyTo",
"Type": "T0"
},
{
"Name": "modelState",
"Type": "Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary"
}
],
"ReturnType": "System.Void",
"Static": true,
"Extension": true,
"Visibility": "Public",
"GenericParameter": [
{
"ParameterName": "T",
"ParameterPosition": 0,
"Class": true,
"BaseTypeOrInterfaces": []
}
]
},
{
"Kind": "Method",
"Name": "ApplyTo<T0>",
"Parameters": [
{
"Name": "patchDoc",
"Type": "Microsoft.AspNetCore.JsonPatch.JsonPatchDocument<T0>"
},
{
"Name": "objectToApplyTo",
"Type": "T0"
},
{
"Name": "modelState",
"Type": "Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary"
},
{
"Name": "prefix",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Static": true,
"Extension": true,
"Visibility": "Public",
"GenericParameter": [
{
"ParameterName": "T",
"ParameterPosition": 0,
"Class": true,
"BaseTypeOrInterfaces": []
}
]
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.JsonResult",
"Visibility": "Public",
"Kind": "Class",
"BaseType": "Microsoft.AspNetCore.Mvc.ActionResult",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "ExecuteResultAsync",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.ActionContext"
}
],
"ReturnType": "System.Threading.Tasks.Task",
"Virtual": true,
"Override": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.IActionResult",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ContentType",
"Parameters": [],
"ReturnType": "System.String",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_ContentType",
"Parameters": [
{
"Name": "value",
"Type": "System.String"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_SerializerSettings",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializerSettings",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_SerializerSettings",
"Parameters": [
{
"Name": "value",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_StatusCode",
"Parameters": [],
"ReturnType": "System.Nullable<System.Int32>",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_StatusCode",
"Parameters": [
{
"Name": "value",
"Type": "System.Nullable<System.Int32>"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_Value",
"Parameters": [],
"ReturnType": "System.Object",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_Value",
"Parameters": [
{
"Name": "value",
"Type": "System.Object"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "value",
"Type": "System.Object"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "value",
"Type": "System.Object"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.MvcJsonOptions",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Infrastructure.ICompatibilitySwitch>"
],
"Members": [
{
"Kind": "Method",
"Name": "get_AllowInputFormatterExceptionMessages",
"Parameters": [],
"ReturnType": "System.Boolean",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "set_AllowInputFormatterExceptionMessages",
"Parameters": [
{
"Name": "value",
"Type": "System.Boolean"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_SerializerSettings",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializerSettings",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter",
"Visibility": "Public",
"Kind": "Class",
"BaseType": "Microsoft.AspNetCore.Mvc.Formatters.TextInputFormatter",
"ImplementedInterfaces": [
"Microsoft.AspNetCore.Mvc.Formatters.IInputFormatterExceptionPolicy"
],
"Members": [
{
"Kind": "Method",
"Name": "get_ExceptionPolicy",
"Parameters": [],
"ReturnType": "Microsoft.AspNetCore.Mvc.Formatters.InputFormatterExceptionPolicy",
"Virtual": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.Formatters.IInputFormatterExceptionPolicy",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_SerializerSettings",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializerSettings",
"Visibility": "Protected",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "ReadRequestBodyAsync",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.Formatters.InputFormatterContext"
},
{
"Name": "encoding",
"Type": "System.Text.Encoding"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.Formatters.InputFormatterResult>",
"Virtual": true,
"Override": true,
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "CreateJsonSerializer",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializer",
"Virtual": true,
"Visibility": "Protected",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "ReleaseJsonSerializer",
"Parameters": [
{
"Name": "serializer",
"Type": "Newtonsoft.Json.JsonSerializer"
}
],
"ReturnType": "System.Void",
"Virtual": true,
"Visibility": "Protected",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
},
{
"Name": "suppressInputFormatterBuffering",
"Type": "System.Boolean"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
},
{
"Name": "suppressInputFormatterBuffering",
"Type": "System.Boolean"
},
{
"Name": "allowInputFormatterExceptionMessages",
"Type": "System.Boolean"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
},
{
"Name": "options",
"Type": "Microsoft.AspNetCore.Mvc.MvcOptions"
},
{
"Name": "jsonOptions",
"Type": "Microsoft.AspNetCore.Mvc.MvcJsonOptions"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter",
"Visibility": "Public",
"Kind": "Class",
"BaseType": "Microsoft.AspNetCore.Mvc.Formatters.TextOutputFormatter",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "get_SerializerSettings",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializerSettings",
"Visibility": "Protected",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_PublicSerializerSettings",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializerSettings",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "WriteObject",
"Parameters": [
{
"Name": "writer",
"Type": "System.IO.TextWriter"
},
{
"Name": "value",
"Type": "System.Object"
}
],
"ReturnType": "System.Void",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "CreateJsonWriter",
"Parameters": [
{
"Name": "writer",
"Type": "System.IO.TextWriter"
}
],
"ReturnType": "Newtonsoft.Json.JsonWriter",
"Virtual": true,
"Visibility": "Protected",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "CreateJsonSerializer",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializer",
"Virtual": true,
"Visibility": "Protected",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "WriteResponseBodyAsync",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.Formatters.OutputFormatterWriteContext"
},
{
"Name": "selectedEncoding",
"Type": "System.Text.Encoding"
}
],
"ReturnType": "System.Threading.Tasks.Task",
"Virtual": true,
"Override": true,
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.Formatters.JsonPatchInputFormatter",
"Visibility": "Public",
"Kind": "Class",
"BaseType": "Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter",
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "CanRead",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.Formatters.InputFormatterContext"
}
],
"ReturnType": "System.Boolean",
"Virtual": true,
"Override": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.Formatters.IInputFormatter",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "get_ExceptionPolicy",
"Parameters": [],
"ReturnType": "Microsoft.AspNetCore.Mvc.Formatters.InputFormatterExceptionPolicy",
"Virtual": true,
"Override": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.Formatters.IInputFormatterExceptionPolicy",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "ReadRequestBodyAsync",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.Formatters.InputFormatterContext"
},
{
"Name": "encoding",
"Type": "System.Text.Encoding"
}
],
"ReturnType": "System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.Formatters.InputFormatterResult>",
"Virtual": true,
"Override": true,
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
},
{
"Name": "suppressInputFormatterBuffering",
"Type": "System.Boolean"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
},
{
"Name": "suppressInputFormatterBuffering",
"Type": "System.Boolean"
},
{
"Name": "allowInputFormatterExceptionMessages",
"Type": "System.Boolean"
}
],
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "logger",
"Type": "Microsoft.Extensions.Logging.ILogger"
},
{
"Name": "serializerSettings",
"Type": "Newtonsoft.Json.JsonSerializerSettings"
},
{
"Name": "charPool",
"Type": "System.Buffers.ArrayPool<System.Char>"
},
{
"Name": "objectPoolProvider",
"Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider"
},
{
"Name": "options",
"Type": "Microsoft.AspNetCore.Mvc.MvcOptions"
},
{
"Name": "jsonOptions",
"Type": "Microsoft.AspNetCore.Mvc.MvcJsonOptions"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.Formatters.JsonSerializerSettingsProvider",
"Visibility": "Public",
"Kind": "Class",
"Abstract": true,
"Static": true,
"Sealed": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "CreateSerializerSettings",
"Parameters": [],
"ReturnType": "Newtonsoft.Json.JsonSerializerSettings",
"Static": true,
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.AspNetCore.Mvc.Formatters.Json.JsonPatchOperationsArrayProvider",
"Visibility": "Public",
"Kind": "Class",
"ImplementedInterfaces": [
"Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionProvider"
],
"Members": [
{
"Kind": "Method",
"Name": "get_Order",
"Parameters": [],
"ReturnType": "System.Int32",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionProvider",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "OnProvidersExecuting",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionProviderContext"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionProvider",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "OnProvidersExecuted",
"Parameters": [
{
"Name": "context",
"Type": "Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescriptionProviderContext"
}
],
"ReturnType": "System.Void",
"Sealed": true,
"Virtual": true,
"ImplementedInterface": "Microsoft.AspNetCore.Mvc.ApiExplorer.IApiDescriptionProvider",
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Constructor",
"Name": ".ctor",
"Parameters": [
{
"Name": "modelMetadataProvider",
"Type": "Microsoft.AspNetCore.Mvc.ModelBinding.IModelMetadataProvider"
}
],
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.Extensions.DependencyInjection.MvcJsonMvcBuilderExtensions",
"Visibility": "Public",
"Kind": "Class",
"Abstract": true,
"Static": true,
"Sealed": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "AddJsonOptions",
"Parameters": [
{
"Name": "builder",
"Type": "Microsoft.Extensions.DependencyInjection.IMvcBuilder"
},
{
"Name": "setupAction",
"Type": "System.Action<Microsoft.AspNetCore.Mvc.MvcJsonOptions>"
}
],
"ReturnType": "Microsoft.Extensions.DependencyInjection.IMvcBuilder",
"Static": true,
"Extension": true,
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
},
{
"Name": "Microsoft.Extensions.DependencyInjection.MvcJsonMvcCoreBuilderExtensions",
"Visibility": "Public",
"Kind": "Class",
"Abstract": true,
"Static": true,
"Sealed": true,
"ImplementedInterfaces": [],
"Members": [
{
"Kind": "Method",
"Name": "AddJsonFormatters",
"Parameters": [
{
"Name": "builder",
"Type": "Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder"
}
],
"ReturnType": "Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder",
"Static": true,
"Extension": true,
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "AddJsonFormatters",
"Parameters": [
{
"Name": "builder",
"Type": "Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder"
},
{
"Name": "setupAction",
"Type": "System.Action<Newtonsoft.Json.JsonSerializerSettings>"
}
],
"ReturnType": "Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder",
"Static": true,
"Extension": true,
"Visibility": "Public",
"GenericParameter": []
},
{
"Kind": "Method",
"Name": "AddJsonOptions",
"Parameters": [
{
"Name": "builder",
"Type": "Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder"
},
{
"Name": "setupAction",
"Type": "System.Action<Microsoft.AspNetCore.Mvc.MvcJsonOptions>"
}
],
"ReturnType": "Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder",
"Static": true,
"Extension": true,
"Visibility": "Public",
"GenericParameter": []
}
],
"GenericParameters": []
}
]
}

View File

@ -0,0 +1,63 @@
// 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 Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
internal class AnnotatedProblemDetails
{
/// <remarks>
/// Required for JSON.NET deserialization.
/// </remarks>
public AnnotatedProblemDetails() { }
public AnnotatedProblemDetails(ProblemDetails problemDetails)
{
Detail = problemDetails.Detail;
Instance = problemDetails.Instance;
Status = problemDetails.Status;
Title = problemDetails.Title;
Type = problemDetails.Type;
foreach (var kvp in problemDetails.Extensions)
{
Extensions[kvp.Key] = kvp.Value;
}
}
[JsonProperty(PropertyName = "type", NullValueHandling = NullValueHandling.Ignore)]
public string Type { get; set; }
[JsonProperty(PropertyName = "title", NullValueHandling = NullValueHandling.Ignore)]
public string Title { get; set; }
[JsonProperty(PropertyName = "status", NullValueHandling = NullValueHandling.Ignore)]
public int? Status { get; set; }
[JsonProperty(PropertyName = "detail", NullValueHandling = NullValueHandling.Ignore)]
public string Detail { get; set; }
[JsonProperty(PropertyName = "instance", NullValueHandling = NullValueHandling.Ignore)]
public string Instance { get; set; }
[JsonExtensionData]
public IDictionary<string, object> Extensions { get; } = new Dictionary<string, object>(StringComparer.Ordinal);
public void CopyTo(ProblemDetails problemDetails)
{
problemDetails.Type = Type;
problemDetails.Title = Title;
problemDetails.Status = Status;
problemDetails.Instance = Instance;
problemDetails.Detail = Detail;
foreach (var kvp in Extensions)
{
problemDetails.Extensions[kvp.Key] = kvp.Value;
}
}
}
}

View File

@ -8,22 +8,22 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
internal class TempDataSerializer
internal class BsonTempDataSerializer : TempDataSerializer
{
private readonly JsonSerializer _jsonSerializer =
JsonSerializer.Create(JsonSerializerSettingsProvider.CreateSerializerSettings());
private static readonly MethodInfo _convertArrayMethodInfo = typeof(TempDataSerializer).GetMethod(
private static readonly MethodInfo _convertArrayMethodInfo = typeof(BsonTempDataSerializer).GetMethod(
nameof(ConvertArray), BindingFlags.Static | BindingFlags.NonPublic);
private static readonly MethodInfo _convertDictionaryMethodInfo = typeof(TempDataSerializer).GetMethod(
private static readonly MethodInfo _convertDictionaryMethodInfo = typeof(BsonTempDataSerializer).GetMethod(
nameof(ConvertDictionary), BindingFlags.Static | BindingFlags.NonPublic);
private static readonly ConcurrentDictionary<Type, Func<JArray, object>> _arrayConverters =
@ -43,7 +43,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
{ JTokenType.Uri, typeof(Uri) },
};
public IDictionary<string, object> Deserialize(byte[] value)
public override IDictionary<string, object> Deserialize(byte[] value)
{
Dictionary<string, object> tempDataDictionary;
@ -124,7 +124,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
return convertedDictionary;
}
public byte[] Serialize(IDictionary<string, object> values)
public override byte[] Serialize(IDictionary<string, object> values)
{
var hasValues = (values != null && values.Count > 0);
if (hasValues)
@ -165,7 +165,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
}
}
public static bool CanSerializeType(Type typeToSerialize, out string errorMessage)
private static bool CanSerializeType(Type typeToSerialize, out string errorMessage)
{
typeToSerialize = typeToSerialize ?? throw new ArgumentNullException(nameof(typeToSerialize));
@ -195,7 +195,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
if (genericTypeArguments[0] != typeof(string))
{
errorMessage = Resources.FormatTempData_CannotSerializeDictionary(
typeof(TempDataSerializer).FullName,
typeof(BsonTempDataSerializer).FullName,
genericTypeArguments[0],
typeof(string).FullName);
return false;
@ -211,7 +211,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
if (!IsSimpleType(actualType))
{
errorMessage = Resources.FormatTempData_CannotSerializeType(
typeof(TempDataSerializer).FullName,
typeof(BsonTempDataSerializer).FullName,
actualType);
return false;
}

View File

@ -3,13 +3,13 @@
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters.Json;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.Extensions.DependencyInjection
{
public static class MvcJsonOptionsExtensions
public static class MvcNewtonsoftJsonOptionsExtensions
{
/// <summary>
/// Configures the casing behavior of JSON serialization to use camel case for property names,
@ -18,10 +18,10 @@ namespace Microsoft.Extensions.DependencyInjection
/// <remarks>
/// This method modifies <see cref="JsonSerializerSettings.ContractResolver"/>.
/// </remarks>
/// <param name="options"><see cref="MvcJsonOptions"/></param>
/// <param name="options"><see cref="MvcNewtonsoftJsonOptions"/></param>
/// <param name="processDictionaryKeys">If true will camel case dictionary keys and properties of dynamic objects.</param>
/// <returns><see cref="MvcJsonOptions"/> with camel case settings.</returns>
public static MvcJsonOptions UseCamelCasing(this MvcJsonOptions options, bool processDictionaryKeys)
/// <returns><see cref="MvcNewtonsoftJsonOptions"/> with camel case settings.</returns>
public static MvcNewtonsoftJsonOptions UseCamelCasing(this MvcNewtonsoftJsonOptions options, bool processDictionaryKeys)
{
if (options == null)
{
@ -57,9 +57,9 @@ namespace Microsoft.Extensions.DependencyInjection
/// <remarks>
/// This method modifies <see cref="JsonSerializerSettings.ContractResolver"/>.
/// </remarks>
/// <param name="options"><see cref="MvcJsonOptions"/></param>
/// <returns><see cref="MvcJsonOptions"/> with member casing settings.</returns>
public static MvcJsonOptions UseMemberCasing(this MvcJsonOptions options)
/// <param name="options"><see cref="MvcNewtonsoftJsonOptions"/></param>
/// <returns><see cref="MvcNewtonsoftJsonOptions"/> with member casing settings.</returns>
public static MvcNewtonsoftJsonOptions UseMemberCasing(this MvcNewtonsoftJsonOptions options)
{
if (options == null)
{

View File

@ -5,28 +5,29 @@ using System;
using System.Buffers;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using Microsoft.AspNetCore.Mvc.Formatters;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Sets up JSON formatter options for <see cref="MvcOptions"/>.
/// </summary>
internal class MvcJsonMvcOptionsSetup : IConfigureOptions<MvcOptions>
internal class NewtonosftJsonMvcOptionsSetup : IConfigureOptions<MvcOptions>
{
private readonly ILoggerFactory _loggerFactory;
private readonly MvcJsonOptions _jsonOptions;
private readonly MvcNewtonsoftJsonOptions _jsonOptions;
private readonly ArrayPool<char> _charPool;
private readonly ObjectPoolProvider _objectPoolProvider;
public MvcJsonMvcOptionsSetup(
public NewtonosftJsonMvcOptionsSetup(
ILoggerFactory loggerFactory,
IOptions<MvcJsonOptions> jsonOptions,
IOptions<MvcNewtonsoftJsonOptions> jsonOptions,
ArrayPool<char> charPool,
ObjectPoolProvider objectPoolProvider)
{
@ -58,13 +59,13 @@ namespace Microsoft.Extensions.DependencyInjection
public void Configure(MvcOptions options)
{
options.OutputFormatters.Add(new JsonOutputFormatter(_jsonOptions.SerializerSettings, _charPool));
options.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(_jsonOptions.SerializerSettings, _charPool));
// Register JsonPatchInputFormatter before JsonInputFormatter, otherwise
// JsonInputFormatter would consume "application/json-patch+json" requests
// before JsonPatchInputFormatter gets to see them.
var jsonInputPatchLogger = _loggerFactory.CreateLogger<JsonPatchInputFormatter>();
options.InputFormatters.Add(new JsonPatchInputFormatter(
var jsonInputPatchLogger = _loggerFactory.CreateLogger<NewtonsoftJsonPatchInputFormatter>();
options.InputFormatters.Add(new NewtonsoftJsonPatchInputFormatter(
jsonInputPatchLogger,
_jsonOptions.SerializerSettings,
_charPool,
@ -72,8 +73,8 @@ namespace Microsoft.Extensions.DependencyInjection
options,
_jsonOptions));
var jsonInputLogger = _loggerFactory.CreateLogger<JsonInputFormatter>();
options.InputFormatters.Add(new JsonInputFormatter(
var jsonInputLogger = _loggerFactory.CreateLogger<NewtonsoftJsonInputFormatter>();
options.InputFormatters.Add(new NewtonsoftJsonInputFormatter(
jsonInputLogger,
_jsonOptions.SerializerSettings,
_charPool,

View File

@ -0,0 +1,56 @@
// 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 Microsoft.AspNetCore.Mvc;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extensions methods for configuring MVC via an <see cref="IMvcBuilder"/>.
/// </summary>
public static class NewtonsoftJsonMvcBuilderExtensions
{
/// <summary>
/// Configures Newtonsoft.Json specific features such as input and output formatters.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddNewtonsoftJson(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
NewtonsoftJsonMvcCoreBuilderExtensions.AddServicesCore(builder.Services);
return builder;
}
/// <summary>
/// Configures Newtonsoft.Json specific features such as input and output formatters.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">Callback to configure <see cref="MvcNewtonsoftJsonOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddNewtonsoftJson(
this IMvcBuilder builder,
Action<MvcNewtonsoftJsonOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
NewtonsoftJsonMvcCoreBuilderExtensions.AddServicesCore(builder.Services);
builder.Services.Configure(setupAction);
return builder;
}
}
}

View File

@ -0,0 +1,110 @@
// 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.Buffers;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.DependencyInjection
{
public static class NewtonsoftJsonMvcCoreBuilderExtensions
{
/// <summary>
/// Configures Newtonsoft.Json specific features such as input and output formatters.
/// </summary>
/// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
/// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
public static IMvcCoreBuilder AddNewtonsoftJson(this IMvcCoreBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddServicesCore(builder.Services);
return builder;
}
/// <summary>
/// Configures Newtonsoft.Json specific features such as input and output formatters.
/// </summary>
/// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param>
/// <param name="setupAction">Callback to configure <see cref="MvcNewtonsoftJsonOptions"/>.</param>
/// <returns>The <see cref="IMvcCoreBuilder"/>.</returns>
public static IMvcCoreBuilder AddNewtonsoftJson(
this IMvcCoreBuilder builder,
Action<MvcNewtonsoftJsonOptions> setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
AddServicesCore(builder.Services);
builder.Services.Configure(setupAction);
return builder;
}
// Internal for testing.
internal static void AddServicesCore(IServiceCollection services)
{
services.TryAddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, NewtonosftJsonMvcOptionsSetup>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IApiDescriptionProvider, JsonPatchOperationsArrayProvider>());
services.TryAddSingleton<IActionResultExecutor<JsonResult>, JsonResultExecutor>();
var viewFeaturesAssembly = typeof(IHtmlHelper).Assembly;
var tempDataSerializer = services.FirstOrDefault(f =>
f.ServiceType == typeof(TempDataSerializer) &&
f.ImplementationType?.Assembly == viewFeaturesAssembly &&
f.ImplementationType.FullName == "Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure.DefaultTempDataSerializer");
if (tempDataSerializer != null)
{
// Replace the default implementation of TempDataSerializer
services.Remove(tempDataSerializer);
}
services.TryAddSingleton<TempDataSerializer, BsonTempDataSerializer>();
//
// JSON Helper
//
var jsonHelper = services.FirstOrDefault(
f => f.ServiceType == typeof(IJsonHelper) &&
f.ImplementationType?.Assembly == viewFeaturesAssembly &&
f.ImplementationType.FullName == "Microsoft.AspNetCore.Mvc.Rendering.DefaultJsonHelper");
if (jsonHelper != null)
{
services.Remove(jsonHelper);
}
services.TryAddSingleton<IJsonHelper, NewtonsoftJsonHelper>();
services.TryAdd(ServiceDescriptor.Singleton(serviceProvider =>
{
var options = serviceProvider.GetRequiredService<IOptions<MvcNewtonsoftJsonOptions>>().Value;
var charPool = serviceProvider.GetRequiredService<ArrayPool<char>>();
return new NewtonsoftJsonOutputFormatter(options.SerializerSettings, charPool);
}));
}
}
}

View File

@ -5,7 +5,7 @@ using System;
using System.Buffers;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
internal class JsonArrayPool<T> : IArrayPool<T>
{

View File

@ -0,0 +1,60 @@
// 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 Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
/// <summary>
/// Newtonsoft.Json specific extensions to <see cref="IJsonHelper"/>.
/// </summary>
public static class JsonHelperExtensions
{
/// <summary>
/// Returns serialized JSON for the <paramref name="value"/>.
/// </summary>
/// <param name="jsonHelper">The <see cref="IJsonHelper"/>.</param>
/// <param name="value">The value to serialize as JSON.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/> to be used by the serializer.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the serialized JSON.</returns>
public static IHtmlContent Serialize(
this IJsonHelper jsonHelper,
object value,
JsonSerializerSettings serializerSettings)
{
if (jsonHelper == null)
{
throw new ArgumentNullException(nameof(jsonHelper));
}
if (!(jsonHelper is NewtonsoftJsonHelper newtonsoftJsonHelper))
{
var message = Resources.FormatJsonHelperMustBeAnInstanceOfNewtonsoftJson(
nameof(jsonHelper),
nameof(IJsonHelper),
typeof(JsonHelperExtensions).Assembly.GetName().Name,
nameof(NewtonsoftJsonMvcBuilderExtensions.AddNewtonsoftJson));
throw new ArgumentException(message, nameof(jsonHelper));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (serializerSettings == null)
{
throw new ArgumentNullException(nameof(serializerSettings));
}
return newtonsoftJsonHelper.Serialize(value, serializerSettings);
}
}
}

View File

@ -8,19 +8,19 @@ using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Microsoft.AspNetCore.Mvc.Formatters.Json
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// Implements a provider of <see cref="ApiDescription"/> to change parameters of
/// Implements a provider of <see cref="ApiDescription"/> to change parameters of
/// type <see cref="IJsonPatchDocument"/> to an array of <see cref="Operation"/>.
/// </summary>
public class JsonPatchOperationsArrayProvider : IApiDescriptionProvider
internal sealed class JsonPatchOperationsArrayProvider : IApiDescriptionProvider
{
private readonly IModelMetadataProvider _modelMetadataProvider;
/// <summary>
/// Creates a new instance of <see cref="JsonPatchOperationsArrayProvider"/>.
/// </summary>
/// </summary>
/// <param name="modelMetadataProvider">The <see cref="IModelMetadataProvider"/>.</param>
public JsonPatchOperationsArrayProvider(IModelMetadataProvider modelMetadataProvider)
{

View File

@ -5,18 +5,19 @@ using System;
using System.Buffers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// Executes a <see cref="JsonResult"/> to write to the response.
/// </summary>
internal class JsonResultExecutor
internal class JsonResultExecutor : IActionResultExecutor<JsonResult>
{
private static readonly string DefaultContentType = new MediaTypeHeaderValue("application/json")
{
@ -25,7 +26,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
private readonly IHttpResponseStreamWriterFactory _writerFactory;
private readonly ILogger _logger;
private readonly MvcJsonOptions _options;
private readonly MvcNewtonsoftJsonOptions _options;
private readonly IArrayPool<char> _charPool;
/// <summary>
@ -38,7 +39,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
public JsonResultExecutor(
IHttpResponseStreamWriterFactory writerFactory,
ILogger<JsonResultExecutor> logger,
IOptions<MvcJsonOptions> options,
IOptions<MvcNewtonsoftJsonOptions> options,
ArrayPool<char> charPool)
{
if (writerFactory == null)
@ -85,6 +86,8 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
throw new ArgumentNullException(nameof(result));
}
var jsonSerializerSettings = GetSerializerSettings(result);
var response = context.HttpContext.Response;
ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
@ -101,8 +104,6 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
response.StatusCode = result.StatusCode.Value;
}
var serializerSettings = result.SerializerSettings ?? _options.SerializerSettings;
_logger.JsonResultExecuting(result.Value);
using (var writer = _writerFactory.CreateWriter(response.Body, resolvedContentTypeEncoding))
{
@ -112,7 +113,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
jsonWriter.CloseOutput = false;
jsonWriter.AutoCompleteOnClose = false;
var jsonSerializer = JsonSerializer.Create(serializerSettings);
var jsonSerializer = JsonSerializer.Create(jsonSerializerSettings);
jsonSerializer.Serialize(jsonWriter, result.Value);
}
@ -121,5 +122,26 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
await writer.FlushAsync();
}
}
private JsonSerializerSettings GetSerializerSettings(JsonResult result)
{
var serializerSettings = result.SerializerSettings;
if (serializerSettings == null)
{
return _options.SerializerSettings;
}
else
{
if (!(serializerSettings is JsonSerializerSettings settingsFromResult))
{
throw new InvalidOperationException(Resources.FormatProperty_MustBeInstanceOfType(
nameof(JsonResult),
nameof(JsonResult.SerializerSettings),
typeof(JsonSerializerSettings)));
}
return settingsFromResult;
}
}
}
}

View File

@ -4,7 +4,7 @@
using Microsoft.Extensions.ObjectPool;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// <see cref="IPooledObjectPolicy{T}"/> for <see cref="JsonSerializer"/>.

View File

@ -4,7 +4,7 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// Helper class which provides <see cref="JsonSerializerSettings"/>.
@ -12,6 +12,8 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
public static class JsonSerializerSettingsProvider
{
private const int DefaultMaxDepth = 32;
private static readonly ProblemDetailsConverter ProblemDetailsConverter = new ProblemDetailsConverter();
private static readonly ValidationProblemDetailsConverter ValidationProblemDetailsConverter = new ValidationProblemDetailsConverter();
// return shared resolver by default for perf so slow reflection logic is cached once
// developers can set their own resolver after the settings are returned if desired
@ -41,6 +43,12 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
// Do not change this setting
// Setting this to None prevents Json.NET from loading malicious, unsafe, or security-sensitive types
TypeNameHandling = TypeNameHandling.None,
Converters =
{
ValidationProblemDetailsConverter,
ProblemDetailsConverter,
}
};
}

View File

@ -3,7 +3,7 @@
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
internal static class MediaTypeHeaderValues
{

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>ASP.NET Core MVC formatters for JSON input and output and for JSON PATCH input using Json.NET.</Description>
<Description>ASP.NET Core MVC features that use Newtonsoft.Json. Includes input and output formatters for JSON and JSON PATCH.</Description>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
@ -13,8 +13,13 @@
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc.Core" />
<Reference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" />
<Reference Include="Microsoft.AspNetCore.JsonPatch" />
<Reference Include="Newtonsoft.Json" />
<Reference Include="Newtonsoft.Json.Bson" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Microsoft.AspNetCore.Mvc.Core\Formatters\ResponseContentTypeHelper.cs" />
</ItemGroup>
</Project>

View File

@ -7,6 +7,7 @@ using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc
@ -14,13 +15,13 @@ namespace Microsoft.AspNetCore.Mvc
/// <summary>
/// Provides programmatic configuration for JSON in the MVC framework.
/// </summary>
public class MvcJsonOptions : IEnumerable<ICompatibilitySwitch>
public class MvcNewtonsoftJsonOptions : IEnumerable<ICompatibilitySwitch>
{
private readonly IReadOnlyList<ICompatibilitySwitch> _switches = Array.Empty<ICompatibilitySwitch>();
/// <summary>
/// Gets or sets a flag to determine whether error messages from JSON deserialization by the
/// <see cref="JsonInputFormatter"/> will be added to the <see cref="ModelStateDictionary"/>. If
/// <see cref="NewtonsoftJsonInputFormatter"/> will be added to the <see cref="ModelStateDictionary"/>. If
/// <see langword="false"/>, a generic error message will be used instead.
/// </summary>
/// <value>

View File

@ -10,25 +10,25 @@ using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// Default implementation of <see cref="IJsonHelper"/>.
/// Newtonsoft.Json based implementation of <see cref="IJsonHelper"/>.
/// </summary>
public class JsonHelper : IJsonHelper
internal class NewtonsoftJsonHelper : IJsonHelper
{
private readonly JsonOutputFormatter _jsonOutputFormatter;
private readonly NewtonsoftJsonOutputFormatter _jsonOutputFormatter;
private readonly ArrayPool<char> _charPool;
/// <summary>
/// Initializes a new instance of <see cref="JsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>.
/// Initializes a new instance of <see cref="NewtonsoftJsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>.
/// </summary>
/// <param name="jsonOutputFormatter">The <see cref="JsonOutputFormatter"/> used to serialize JSON.</param>
/// <param name="jsonOutputFormatter">The <see cref="NewtonsoftJsonOutputFormatter"/> used to serialize JSON.</param>
/// <param name="charPool">
/// The <see cref="ArrayPool{Char}"/> for use with custom <see cref="JsonSerializerSettings"/> (see
/// <see cref="Serialize(object, JsonSerializerSettings)"/>).
/// </param>
public JsonHelper(JsonOutputFormatter jsonOutputFormatter, ArrayPool<char> charPool)
public NewtonsoftJsonHelper(NewtonsoftJsonOutputFormatter jsonOutputFormatter, ArrayPool<char> charPool)
{
if (jsonOutputFormatter == null)
{
@ -60,12 +60,12 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
throw new ArgumentNullException(nameof(serializerSettings));
}
var jsonOutputFormatter = new JsonOutputFormatter(serializerSettings, _charPool);
var jsonOutputFormatter = new NewtonsoftJsonOutputFormatter(serializerSettings, _charPool);
return SerializeInternal(jsonOutputFormatter, value);
}
private IHtmlContent SerializeInternal(JsonOutputFormatter jsonOutputFormatter, object value)
private IHtmlContent SerializeInternal(NewtonsoftJsonOutputFormatter jsonOutputFormatter, object value)
{
var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
jsonOutputFormatter.WriteObject(stringWriter, value);

View File

@ -11,6 +11,7 @@ using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
@ -21,13 +22,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// <summary>
/// A <see cref="TextInputFormatter"/> for JSON content.
/// </summary>
public class JsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy
public class NewtonsoftJsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy
{
private readonly IArrayPool<char> _charPool;
private readonly ILogger _logger;
private readonly ObjectPoolProvider _objectPoolProvider;
private readonly MvcOptions _options;
private readonly MvcJsonOptions _jsonOptions;
private readonly MvcNewtonsoftJsonOptions _jsonOptions;
// These fields are used when one of the legacy constructors is called that doesn't provide the MvcOptions or
// MvcJsonOptions.
@ -37,18 +38,18 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
private ObjectPool<JsonSerializer> _jsonSerializerPool;
/// <summary>
/// Initializes a new instance of <see cref="JsonInputFormatter"/>.
/// Initializes a new instance of <see cref="NewtonsoftJsonInputFormatter"/>.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
/// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param>
[Obsolete("This constructor is obsolete and will be removed in a future version.")]
public JsonInputFormatter(
public NewtonsoftJsonInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
@ -59,19 +60,19 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
}
/// <summary>
/// Initializes a new instance of <see cref="JsonInputFormatter"/>.
/// Initializes a new instance of <see cref="NewtonsoftJsonInputFormatter"/>.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
/// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param>
/// <param name="suppressInputFormatterBuffering">Flag to buffer entire request body before deserializing it.</param>
[Obsolete("This constructor is obsolete and will be removed in a future version.")]
public JsonInputFormatter(
public NewtonsoftJsonInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
@ -84,12 +85,12 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
}
/// <summary>
/// Initializes a new instance of <see cref="JsonInputFormatter"/>.
/// Initializes a new instance of <see cref="NewtonsoftJsonInputFormatter"/>.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
@ -97,7 +98,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// <param name="suppressInputFormatterBuffering">Flag to buffer entire request body before deserializing it.</param>
/// <param name="allowInputFormatterExceptionMessages">If <see langword="true"/>, JSON deserialization exception messages will replaced by a generic message in model state.</param>
[Obsolete("This constructor is obsolete and will be removed in a future version.")]
public JsonInputFormatter(
public NewtonsoftJsonInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
@ -141,25 +142,25 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
}
/// <summary>
/// Initializes a new instance of <see cref="JsonInputFormatter"/>.
/// Initializes a new instance of <see cref="NewtonsoftJsonInputFormatter"/>.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
/// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param>
/// <param name="options">The <see cref="MvcOptions"/>.</param>
/// <param name="jsonOptions">The <see cref="MvcJsonOptions"/>.</param>
public JsonInputFormatter(
/// <param name="jsonOptions">The <see cref="MvcNewtonsoftJsonOptions"/>.</param>
public NewtonsoftJsonInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
ObjectPoolProvider objectPoolProvider,
MvcOptions options,
MvcJsonOptions jsonOptions)
MvcNewtonsoftJsonOptions jsonOptions)
{
if (logger == null)
{
@ -201,7 +202,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{
get
{
if (GetType() == typeof(JsonInputFormatter))
if (GetType() == typeof(NewtonsoftJsonInputFormatter))
{
return InputFormatterExceptionPolicy.MalformedInputExceptions;
}
@ -214,7 +215,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// </summary>
/// <remarks>
/// Any modifications to the <see cref="JsonSerializerSettings"/> object after this
/// <see cref="JsonInputFormatter"/> has been used will have no effect.
/// <see cref="NewtonsoftJsonInputFormatter"/> has been used will have no effect.
/// </remarks>
protected JsonSerializerSettings SerializerSettings { get; }

View File

@ -4,15 +4,15 @@
using System;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
internal static class MvcJsonLoggerExtensions
internal static class NewtonsoftJsonLoggerExtensions
{
private static readonly Action<ILogger, Exception> _jsonInputFormatterCrashed;
private static readonly Action<ILogger, string, Exception> _jsonResultExecuting;
static MvcJsonLoggerExtensions()
static NewtonsoftJsonLoggerExtensions()
{
_jsonInputFormatterCrashed = LoggerMessage.Define(
LogLevel.Debug,

View File

@ -7,6 +7,7 @@ using System.ComponentModel;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.Formatters
@ -14,7 +15,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// <summary>
/// A <see cref="TextOutputFormatter"/> for JSON content.
/// </summary>
public class JsonOutputFormatter : TextOutputFormatter
public class NewtonsoftJsonOutputFormatter : TextOutputFormatter
{
private readonly IArrayPool<char> _charPool;
@ -23,15 +24,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
private JsonSerializer _serializer;
/// <summary>
/// Initializes a new <see cref="JsonOutputFormatter"/> instance.
/// Initializes a new <see cref="NewtonsoftJsonOutputFormatter"/> instance.
/// </summary>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
public JsonOutputFormatter(JsonSerializerSettings serializerSettings, ArrayPool<char> charPool)
public NewtonsoftJsonOutputFormatter(JsonSerializerSettings serializerSettings, ArrayPool<char> charPool)
{
if (serializerSettings == null)
{
@ -58,7 +59,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// </summary>
/// <remarks>
/// Any modifications to the <see cref="JsonSerializerSettings"/> object after this
/// <see cref="JsonOutputFormatter"/> has been used will have no effect.
/// <see cref="NewtonsoftJsonOutputFormatter"/> has been used will have no effect.
/// </remarks>
protected JsonSerializerSettings SerializerSettings { get; }
@ -67,7 +68,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// </summary>
/// <remarks>
/// Any modifications to the <see cref="JsonSerializerSettings"/> object after this
/// <see cref="JsonOutputFormatter"/> has been used will have no effect.
/// <see cref="NewtonsoftJsonOutputFormatter"/> has been used will have no effect.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public JsonSerializerSettings PublicSerializerSettings => SerializerSettings;

View File

@ -7,6 +7,7 @@ using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Newtonsoft.Json;
@ -16,21 +17,21 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// <summary>
/// A <see cref="TextInputFormatter"/> for JSON Patch (application/json-patch+json) content.
/// </summary>
public class JsonPatchInputFormatter : JsonInputFormatter
public class NewtonsoftJsonPatchInputFormatter : NewtonsoftJsonInputFormatter
{
/// <summary>
/// Initializes a new <see cref="JsonPatchInputFormatter"/> instance.
/// Initializes a new <see cref="NewtonsoftJsonPatchInputFormatter"/> instance.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
/// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param>
[Obsolete("This constructor is obsolete and will be removed in a future version.")]
public JsonPatchInputFormatter(
public NewtonsoftJsonPatchInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
@ -40,19 +41,19 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
}
/// <summary>
/// Initializes a new <see cref="JsonPatchInputFormatter"/> instance.
/// Initializes a new <see cref="NewtonsoftJsonPatchInputFormatter"/> instance.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
/// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param>
/// <param name="suppressInputFormatterBuffering">Flag to buffer entire request body before deserializing it.</param>
[Obsolete("This constructor is obsolete and will be removed in a future version.")]
public JsonPatchInputFormatter(
public NewtonsoftJsonPatchInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
@ -63,12 +64,12 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
}
/// <summary>
/// Initializes a new <see cref="JsonPatchInputFormatter"/> instance.
/// Initializes a new <see cref="NewtonsoftJsonPatchInputFormatter"/> instance.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
@ -78,7 +79,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
/// If <see langword="false"/>, JSON deserialization exception messages will replaced by a generic message in model state.
/// </param>
[Obsolete("This constructor is obsolete and will be removed in a future version.")]
public JsonPatchInputFormatter(
public NewtonsoftJsonPatchInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
@ -94,25 +95,25 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
}
/// <summary>
/// Initializes a new <see cref="JsonPatchInputFormatter"/> instance.
/// Initializes a new <see cref="NewtonsoftJsonPatchInputFormatter"/> instance.
/// </summary>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/>. Should be either the application-wide settings
/// (<see cref="MvcJsonOptions.SerializerSettings"/>) or an instance
/// (<see cref="MvcNewtonsoftJsonOptions.SerializerSettings"/>) or an instance
/// <see cref="JsonSerializerSettingsProvider.CreateSerializerSettings"/> initially returned.
/// </param>
/// <param name="charPool">The <see cref="ArrayPool{Char}"/>.</param>
/// <param name="objectPoolProvider">The <see cref="ObjectPoolProvider"/>.</param>
/// <param name="options">The <see cref="MvcOptions"/>.</param>
/// <param name="jsonOptions">The <see cref="MvcJsonOptions"/>.</param>
public JsonPatchInputFormatter(
/// <param name="jsonOptions">The <see cref="MvcNewtonsoftJsonOptions"/>.</param>
public NewtonsoftJsonPatchInputFormatter(
ILogger logger,
JsonSerializerSettings serializerSettings,
ArrayPool<char> charPool,
ObjectPoolProvider objectPoolProvider,
MvcOptions options,
MvcJsonOptions jsonOptions)
MvcNewtonsoftJsonOptions jsonOptions)
: base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions)
{
// Clear all values and only include json-patch+json value.
@ -126,7 +127,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{
get
{
if (GetType() == typeof(JsonPatchInputFormatter))
if (GetType() == typeof(NewtonsoftJsonPatchInputFormatter))
{
return InputFormatterExceptionPolicy.MalformedInputExceptions;
}

View File

@ -0,0 +1,50 @@
// 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 Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// A RFC 7807 compliant <see cref="JsonConverter"/> for <see cref="ProblemDetails"/>.
/// </summary>
public sealed class ProblemDetailsConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ProblemDetails);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var annotatedProblemDetails = serializer.Deserialize<AnnotatedProblemDetails>(reader);
if (annotatedProblemDetails == null)
{
return null;
}
var problemDetails = (ProblemDetails)existingValue ?? new ProblemDetails();
annotatedProblemDetails.CopyTo(problemDetails);
return problemDetails;
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var problemDetails = (ProblemDetails)value;
var annotatedProblemDetails = new AnnotatedProblemDetails(problemDetails);
serializer.Serialize(writer, annotatedProblemDetails);
}
}
}

View File

@ -4,5 +4,5 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Json.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.NewtonsoftJson.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]

View File

@ -0,0 +1,128 @@
// <auto-generated />
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNetCore.Mvc.NewtonsoftJson.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// {0} cannot be null.
/// </summary>
internal static string ContractResolverCannotBeNull
{
get => GetString("ContractResolverCannotBeNull");
}
/// <summary>
/// {0} cannot be null.
/// </summary>
internal static string FormatContractResolverCannotBeNull(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("ContractResolverCannotBeNull"), p0);
/// <summary>
/// Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.
/// </summary>
internal static string InvalidContractResolverForJsonCasingConfiguration
{
get => GetString("InvalidContractResolverForJsonCasingConfiguration");
}
/// <summary>
/// Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.
/// </summary>
internal static string FormatInvalidContractResolverForJsonCasingConfiguration(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("InvalidContractResolverForJsonCasingConfiguration"), p0, p1);
/// <summary>
/// Parameter '{0}' must be an instance of {1} provided by the '{2}' package. Configure the correct instance using '{3}' in your startup.
/// </summary>
internal static string JsonHelperMustBeAnInstanceOfNewtonsoftJson
{
get => GetString("JsonHelperMustBeAnInstanceOfNewtonsoftJson");
}
/// <summary>
/// Parameter '{0}' must be an instance of {1} provided by the '{2}' package. Configure the correct instance using '{3}' in your startup.
/// </summary>
internal static string FormatJsonHelperMustBeAnInstanceOfNewtonsoftJson(object p0, object p1, object p2, object p3)
=> string.Format(CultureInfo.CurrentCulture, GetString("JsonHelperMustBeAnInstanceOfNewtonsoftJson"), p0, p1, p2, p3);
/// <summary>
/// Property '{0}.{1}' must be an instance of type '{2}'.
/// </summary>
internal static string Property_MustBeInstanceOfType
{
get => GetString("Property_MustBeInstanceOfType");
}
/// <summary>
/// Property '{0}.{1}' must be an instance of type '{2}'.
/// </summary>
internal static string FormatProperty_MustBeInstanceOfType(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("Property_MustBeInstanceOfType"), p0, p1, p2);
/// <summary>
/// Cannot deserialize {0} of type '{1}'.
/// </summary>
internal static string TempData_CannotDeserializeToken
{
get => GetString("TempData_CannotDeserializeToken");
}
/// <summary>
/// Cannot deserialize {0} of type '{1}'.
/// </summary>
internal static string FormatTempData_CannotDeserializeToken(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempData_CannotDeserializeToken"), p0, p1);
/// <summary>
/// The '{0}' cannot serialize a dictionary with a key of type '{1}'. The key must be of type '{2}'.
/// </summary>
internal static string TempData_CannotSerializeDictionary
{
get => GetString("TempData_CannotSerializeDictionary");
}
/// <summary>
/// The '{0}' cannot serialize a dictionary with a key of type '{1}'. The key must be of type '{2}'.
/// </summary>
internal static string FormatTempData_CannotSerializeDictionary(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempData_CannotSerializeDictionary"), p0, p1, p2);
/// <summary>
/// The '{0}' cannot serialize an object of type '{1}'.
/// </summary>
internal static string TempData_CannotSerializeType
{
get => GetString("TempData_CannotSerializeType");
}
/// <summary>
/// The '{0}' cannot serialize an object of type '{1}'.
/// </summary>
internal static string FormatTempData_CannotSerializeType(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempData_CannotSerializeType"), p0, p1);
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
@ -123,4 +123,19 @@
<data name="InvalidContractResolverForJsonCasingConfiguration" xml:space="preserve">
<value>Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.</value>
</data>
<data name="JsonHelperMustBeAnInstanceOfNewtonsoftJson" xml:space="preserve">
<value>Parameter '{0}' must be an instance of {1} provided by the '{2}' package. Configure the correct instance using '{3}' in your startup.</value>
</data>
<data name="Property_MustBeInstanceOfType" xml:space="preserve">
<value>Property '{0}.{1}' must be an instance of type '{2}'.</value>
</data>
<data name="TempData_CannotDeserializeToken" xml:space="preserve">
<value>Cannot deserialize {0} of type '{1}'.</value>
</data>
<data name="TempData_CannotSerializeDictionary" xml:space="preserve">
<value>The '{0}' cannot serialize a dictionary with a key of type '{1}'. The key must be of type '{2}'.</value>
</data>
<data name="TempData_CannotSerializeType" xml:space="preserve">
<value>The '{0}' cannot serialize an object of type '{1}'.</value>
</data>
</root>

View File

@ -0,0 +1,81 @@
// 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 Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
/// <summary>
/// A RFC 7807 compliant <see cref="JsonConverter"/> for <see cref="ValidationProblemDetails"/>.
/// </summary>
public sealed class ValidationProblemDetailsConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ValidationProblemDetails);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var annotatedProblemDetails = serializer.Deserialize<AnnotatedValidationProblemDetails>(reader);
if (annotatedProblemDetails == null)
{
return null;
}
var problemDetails = (ValidationProblemDetails)existingValue ?? new ValidationProblemDetails();
annotatedProblemDetails.CopyTo(problemDetails);
return problemDetails;
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var problemDetails = (ValidationProblemDetails)value;
var annotatedProblemDetails = new AnnotatedValidationProblemDetails(problemDetails);
serializer.Serialize(writer, annotatedProblemDetails);
}
private class AnnotatedValidationProblemDetails : AnnotatedProblemDetails
{
/// <remarks>
/// Required for JSON.NET deserialization.
/// </remarks>
public AnnotatedValidationProblemDetails() { }
public AnnotatedValidationProblemDetails(ValidationProblemDetails problemDetails)
: base(problemDetails)
{
foreach (var kvp in problemDetails.Errors)
{
Errors[kvp.Key] = kvp.Value;
}
}
[JsonProperty(PropertyName = "errors")]
public IDictionary<string, string[]> Errors { get; } = new Dictionary<string, string[]>(StringComparer.Ordinal);
public void CopyTo(ValidationProblemDetails problemDetails)
{
base.CopyTo(problemDetails);
foreach (var kvp in Errors)
{
problemDetails.Errors[kvp.Key] = kvp.Value;
}
}
}
}
}

View File

@ -4,17 +4,17 @@
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Filters;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
namespace Microsoft.AspNetCore.Mvc.ApplicationModels
{
internal class TempDataFilterPageApplicationModelProvider : IPageApplicationModelProvider
{
private readonly MvcViewOptions _options;
private readonly TempDataSerializer _tempDataSerializer;
public TempDataFilterPageApplicationModelProvider(IOptions<MvcViewOptions> options)
public TempDataFilterPageApplicationModelProvider(TempDataSerializer tempDataSerializer)
{
_options = options.Value;
_tempDataSerializer = tempDataSerializer;
}
// The order is set to execute after the DefaultPageApplicationModelProvider.
@ -34,7 +34,7 @@ namespace Microsoft.AspNetCore.Mvc.ApplicationModels
var pageApplicationModel = context.PageApplicationModel;
var handlerType = pageApplicationModel.HandlerType.AsType();
var tempDataProperties = SaveTempDataPropertyFilterBase.GetTempDataProperties(handlerType, _options);
var tempDataProperties = SaveTempDataPropertyFilterBase.GetTempDataProperties(_tempDataSerializer, handlerType);
if (tempDataProperties == null)
{
return;

View File

@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc
{
@ -299,14 +298,13 @@ namespace Microsoft.AspNetCore.Mvc
/// to JSON.
/// </summary>
/// <param name="data">The object to serialize.</param>
/// <param name="serializerSettings">The <see cref="JsonSerializerSettings"/> to be used by
/// the formatter.</param>
/// <param name="serializerSettings">The serializer settings to be used by the formatter.</param>
/// <returns>The created <see cref="JsonResult"/> that serializes the specified <paramref name="data"/>
/// as JSON format for the response.</returns>
/// <remarks>Callers should cache an instance of <see cref="JsonSerializerSettings"/> to avoid
/// <remarks>Callers should cache an instance of serializer settings to avoid
/// recreating cached data with each call.</remarks>
[NonAction]
public virtual JsonResult Json(object data, JsonSerializerSettings serializerSettings)
public virtual JsonResult Json(object data, object serializerSettings)
{
if (serializerSettings == null)
{

View File

@ -6,7 +6,7 @@ using System.Collections.Generic;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Filters;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@ -30,11 +30,12 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
public CookieTempDataProvider(
IDataProtectionProvider dataProtectionProvider,
ILoggerFactory loggerFactory,
IOptions<CookieTempDataProviderOptions> options)
IOptions<CookieTempDataProviderOptions> options,
TempDataSerializer tempDataSerializer)
{
_dataProtector = dataProtectionProvider.CreateProtector(Purpose);
_logger = loggerFactory.CreateLogger<CookieTempDataProvider>();
_tempDataSerializer = new TempDataSerializer();
_tempDataSerializer = tempDataSerializer;
_chunkingCookieManager = new ChunkingCookieManager();
_options = options.Value;
}

View File

@ -16,6 +16,7 @@ using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Filters;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
@ -169,16 +170,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.TryAddSingleton<IModelExpressionProvider>(s => s.GetRequiredService<ModelExpressionProvider>());
services.TryAddSingleton<ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>();
//
// JSON Helper
//
services.TryAddSingleton<IJsonHelper, JsonHelper>();
services.TryAdd(ServiceDescriptor.Singleton(serviceProvider =>
{
var options = serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value;
var charPool = serviceProvider.GetRequiredService<ArrayPool<char>>();
return new JsonOutputFormatter(options.SerializerSettings, charPool);
}));
services.TryAddSingleton<IJsonHelper, DefaultJsonHelper>();
//
// View Components
@ -212,6 +204,7 @@ namespace Microsoft.Extensions.DependencyInjection
// This does caching so it should stay singleton
services.TryAddSingleton<ITempDataProvider, CookieTempDataProvider>();
services.TryAddSingleton<TempDataSerializer, DefaultTempDataSerializer>();
//
// Antiforgery

View File

@ -5,6 +5,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
@ -80,7 +81,9 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
}
}
public static IReadOnlyList<LifecycleProperty> GetTempDataProperties(Type type, MvcViewOptions viewOptions)
public static IReadOnlyList<LifecycleProperty> GetTempDataProperties(
TempDataSerializer tempDataSerializer,
Type type)
{
List<LifecycleProperty> results = null;
@ -92,7 +95,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
var tempDataAttribute = property.GetCustomAttribute<TempDataAttribute>();
if (tempDataAttribute != null)
{
ValidateProperty(propertyHelper.Property);
ValidateProperty(tempDataSerializer, propertyHelper.Property);
if (results == null)
{
results = new List<LifecycleProperty>();
@ -111,7 +114,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
return results;
}
private static void ValidateProperty(PropertyInfo property)
private static void ValidateProperty(TempDataSerializer tempDataSerializer, PropertyInfo property)
{
if (!(property.SetMethod != null &&
property.SetMethod.IsPublic &&
@ -122,16 +125,13 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
Resources.FormatTempDataProperties_PublicGetterSetter(property.DeclaringType.FullName, property.Name, nameof(TempDataAttribute)));
}
var propertyType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
if (!TempDataSerializer.CanSerializeType(propertyType, out var errorMessage))
if (!tempDataSerializer.CanSerializeType(property.PropertyType))
{
var messageWithPropertyInfo = Resources.FormatTempDataProperties_InvalidType(
property.DeclaringType.FullName,
throw new InvalidOperationException(Resources.FormatTempDataProperties_InvalidType(
tempDataSerializer.GetType().FullName,
TypeNameHelper.GetTypeDisplayName(property.DeclaringType),
property.Name,
nameof(TempDataAttribute));
throw new InvalidOperationException($"{messageWithPropertyInfo} {errorMessage}");
TypeNameHelper.GetTypeDisplayName(property.PropertyType)));
}
}
}

View File

@ -3,17 +3,17 @@
using System;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
{
internal class TempDataApplicationModelProvider : IApplicationModelProvider
{
private readonly MvcViewOptions _options;
private readonly TempDataSerializer _tempDataSerializer;
public TempDataApplicationModelProvider(IOptions<MvcViewOptions> options)
public TempDataApplicationModelProvider(TempDataSerializer tempDataSerializer)
{
_options = options.Value;
_tempDataSerializer = tempDataSerializer;
}
/// <inheritdoc />
@ -37,7 +37,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
{
var modelType = controllerModel.ControllerType.AsType();
var tempDataProperties = SaveTempDataPropertyFilterBase.GetTempDataProperties(modelType, _options);
var tempDataProperties = SaveTempDataPropertyFilterBase.GetTempDataProperties(_tempDataSerializer, modelType);
if (tempDataProperties == null)
{
continue;

View File

@ -0,0 +1,32 @@
// 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 Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure
{
internal class DefaultTempDataSerializer : TempDataSerializer
{
public override IDictionary<string, object> Deserialize(byte[] unprotectedData)
{
throw new InvalidOperationException(Core.Resources.FormatReferenceToNewtonsoftJsonRequired(
Resources.DeserializingTempData,
"Microsoft.AspNetCore.Mvc.NewtonsoftJson",
nameof(IMvcBuilder),
"AddNewtonsoftJson",
"ConfigureServices(...)"));
}
public override byte[] Serialize(IDictionary<string, object> values)
{
throw new InvalidOperationException(Core.Resources.FormatReferenceToNewtonsoftJsonRequired(
Resources.SerializingTempData,
"Microsoft.AspNetCore.Mvc.NewtonsoftJson",
nameof(IMvcBuilder),
"AddNewtonsoftJson",
"ConfigureServices(...)"));
}
}
}

View File

@ -0,0 +1,39 @@
// 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;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure
{
/// <summary>
/// Serializes and deserializes the contents of <see cref="ITempDataDictionary"/>.
/// </summary>
public abstract class TempDataSerializer
{
/// <summary>
/// Deserializes <paramref name="unprotectedData"/> to a <see cref="IDictionary{TKey, TValue}"/>
/// used to initialize an instance of <see cref="ITempDataDictionary"/>.
/// </summary>
/// <param name="unprotectedData">Serialized representation of <see cref="ITempDataDictionary"/>.</param>
/// <returns>The deserialized <see cref="IDictionary{TKey, TValue}"/>.</returns>
public abstract IDictionary<string, object> Deserialize(byte[] unprotectedData);
/// <summary>
/// Serializes the contents of <see cref="ITempDataDictionary"/>.
/// </summary>
/// <param name="values">The contents of <see cref="ITempDataDictionary"/>.</param>
/// <returns>The serialized bytes.</returns>
public abstract byte[] Serialize(IDictionary<string, object> values);
/// <summary>
/// Determines if the serializer supports the specified <paramref name="type"/>.
/// <para>
/// Defaults to returning <see langword="true"/> for all <see cref="Type"/> instances.
/// </para>
/// </summary>
/// <param name="type">The <see cref="Type"/>.</param>
/// <returns><see langword="true"/> if the serializer supports serializing <paramref name="type"/>, otherwise <see langword="false"/>.</returns>
public virtual bool CanSerializeType(Type type) => true;
}
}

View File

@ -16,13 +16,11 @@ Microsoft.AspNetCore.Mvc.ViewComponent</Description>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc.Core" />
<Reference Include="Microsoft.AspNetCore.Mvc.DataAnnotations" />
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" />
<Reference Include="Microsoft.AspNetCore.Antiforgery" />
<Reference Include="Microsoft.AspNetCore.Diagnostics.Abstractions" />
<Reference Include="Microsoft.AspNetCore.Html.Abstractions" />
<Reference Include="Microsoft.Extensions.WebEncoders" />
<Reference Include="Newtonsoft.Json.Bson" />
</ItemGroup>
</Project>

View File

@ -8,6 +8,7 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.TagHelpers, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.NewtonsoftJson.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Razor.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.RazorPages.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.TagHelpers.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]

View File

@ -668,48 +668,6 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
internal static string FormatViewComponentResult_NameOrTypeMustBeSet(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("ViewComponentResult_NameOrTypeMustBeSet"), p0, p1);
/// <summary>
/// Cannot deserialize {0} of type '{1}'.
/// </summary>
internal static string TempData_CannotDeserializeToken
{
get => GetString("TempData_CannotDeserializeToken");
}
/// <summary>
/// Cannot deserialize {0} of type '{1}'.
/// </summary>
internal static string FormatTempData_CannotDeserializeToken(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempData_CannotDeserializeToken"), p0, p1);
/// <summary>
/// The '{0}' cannot serialize a dictionary with a key of type '{1}'. The key must be of type '{2}'.
/// </summary>
internal static string TempData_CannotSerializeDictionary
{
get => GetString("TempData_CannotSerializeDictionary");
}
/// <summary>
/// The '{0}' cannot serialize a dictionary with a key of type '{1}'. The key must be of type '{2}'.
/// </summary>
internal static string FormatTempData_CannotSerializeDictionary(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempData_CannotSerializeDictionary"), p0, p1, p2);
/// <summary>
/// The '{0}' cannot serialize an object of type '{1}'.
/// </summary>
internal static string TempData_CannotSerializeType
{
get => GetString("TempData_CannotSerializeType");
}
/// <summary>
/// The '{0}' cannot serialize an object of type '{1}'.
/// </summary>
internal static string FormatTempData_CannotSerializeType(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempData_CannotSerializeType"), p0, p1);
/// <summary>
/// The collection already contains an entry with key '{0}'.
/// </summary>
@ -794,20 +752,6 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
internal static string FormatViewEnginesAreRequired(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("ViewEnginesAreRequired"), p0, p1, p2);
/// <summary>
/// The '{0}.{1}' property with {2} is invalid.
/// </summary>
internal static string TempDataProperties_InvalidType
{
get => GetString("TempDataProperties_InvalidType");
}
/// <summary>
/// The '{0}.{1}' property with {2} is invalid.
/// </summary>
internal static string FormatTempDataProperties_InvalidType(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempDataProperties_InvalidType"), p0, p1, p2);
/// <summary>
/// The '{0}.{1}' property with {2} is invalid. A property using {2} must have a public getter and setter.
/// </summary>
@ -822,6 +766,48 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
internal static string FormatTempDataProperties_PublicGetterSetter(object p0, object p1, object p2)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempDataProperties_PublicGetterSetter"), p0, p1, p2);
/// <summary>
/// TempData serializer '{0}' cannot serialize property '{1}.{2}' of type '{3}'.
/// </summary>
internal static string TempDataProperties_InvalidType
{
get => GetString("TempDataProperties_InvalidType");
}
/// <summary>
/// TempData serializer '{0}' cannot serialize property '{1}.{2}' of type '{3}'.
/// </summary>
internal static string FormatTempDataProperties_InvalidType(object p0, object p1, object p2, object p3)
=> string.Format(CultureInfo.CurrentCulture, GetString("TempDataProperties_InvalidType"), p0, p1, p2, p3);
/// <summary>
/// Deserializing TempDataDictionary
/// </summary>
internal static string DeserializingTempData
{
get => GetString("DeserializingTempData");
}
/// <summary>
/// Deserializing TempDataDictionary
/// </summary>
internal static string FormatDeserializingTempData()
=> GetString("DeserializingTempData");
/// <summary>
/// Serializing TempDataDictionary
/// </summary>
internal static string SerializingTempData
{
get => GetString("SerializingTempData");
}
/// <summary>
/// Serializing TempDataDictionary
/// </summary>
internal static string FormatSerializingTempData()
=> GetString("SerializingTempData");
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);

View File

@ -0,0 +1,24 @@

// 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 Microsoft.AspNetCore.Html;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
internal class DefaultJsonHelper : IJsonHelper
{
/// <inheritdoc />
public IHtmlContent Serialize(object value)
{
throw new InvalidOperationException(Core.Resources.FormatReferenceToNewtonsoftJsonRequired(
$"{nameof(IJsonHelper)}.{nameof(Serialize)}",
"Microsoft.AspNetCore.Mvc.NewtonsoftJson",
nameof(IMvcBuilder),
"AddNewtonsoftJson",
"ConfigureServices(...)"));
}
}
}

View File

@ -2,7 +2,6 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Html;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.Rendering
{
@ -17,15 +16,5 @@ namespace Microsoft.AspNetCore.Mvc.Rendering
/// <param name="value">The value to serialize as JSON.</param>
/// <returns>A new <see cref="IHtmlContent"/> containing the serialized JSON.</returns>
IHtmlContent Serialize(object value);
/// <summary>
/// Returns serialized JSON for the <paramref name="value"/>.
/// </summary>
/// <param name="value">The value to serialize as JSON.</param>
/// <param name="serializerSettings">
/// The <see cref="JsonSerializerSettings"/> to be used by the serializer.
/// </param>
/// <returns>A new <see cref="IHtmlContent"/> containing the serialized JSON.</returns>
IHtmlContent Serialize(object value, JsonSerializerSettings serializerSettings);
}
}

View File

@ -259,15 +259,6 @@
<data name="ViewComponentResult_NameOrTypeMustBeSet" xml:space="preserve">
<value>Either the '{0}' or '{1}' property must be set in order to invoke a view component.</value>
</data>
<data name="TempData_CannotDeserializeToken" xml:space="preserve">
<value>Cannot deserialize {0} of type '{1}'.</value>
</data>
<data name="TempData_CannotSerializeDictionary" xml:space="preserve">
<value>The '{0}' cannot serialize a dictionary with a key of type '{1}'. The key must be of type '{2}'.</value>
</data>
<data name="TempData_CannotSerializeType" xml:space="preserve">
<value>The '{0}' cannot serialize an object of type '{1}'.</value>
</data>
<data name="Dictionary_DuplicateKey" xml:space="preserve">
<value>The collection already contains an entry with key '{0}'.</value>
</data>
@ -286,10 +277,16 @@
<data name="ViewEnginesAreRequired" xml:space="preserve">
<value>'{0}.{1}' must not be empty. At least one '{2}' is required to locate a view for rendering.</value>
</data>
<data name="TempDataProperties_InvalidType" xml:space="preserve">
<value>The '{0}.{1}' property with {2} is invalid.</value>
</data>
<data name="TempDataProperties_PublicGetterSetter" xml:space="preserve">
<value>The '{0}.{1}' property with {2} is invalid. A property using {2} must have a public getter and setter.</value>
</data>
<data name="TempDataProperties_InvalidType" xml:space="preserve">
<value>TempData serializer '{0}' cannot serialize property '{1}.{2}' of type '{3}'.</value>
</data>
<data name="DeserializingTempData" xml:space="preserve">
<value>Deserializing TempDataDictionary</value>
</data>
<data name="SerializingTempData" xml:space="preserve">
<value>Serializing TempDataDictionary</value>
</data>
</root>

View File

@ -4,7 +4,7 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Filters;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
@ -17,9 +17,9 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
internal const string TempDataSessionStateKey = "__ControllerTempData";
private readonly TempDataSerializer _tempDataSerializer;
public SessionStateTempDataProvider()
public SessionStateTempDataProvider(TempDataSerializer tempDataSerializer)
{
_tempDataSerializer = new TempDataSerializer();
_tempDataSerializer = tempDataSerializer;
}
/// <inheritdoc />

View File

@ -13,7 +13,6 @@
<Reference Include="Microsoft.AspNetCore.Mvc.ApiExplorer" />
<Reference Include="Microsoft.AspNetCore.Mvc.Cors" />
<Reference Include="Microsoft.AspNetCore.Mvc.DataAnnotations" />
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" />
<Reference Include="Microsoft.AspNetCore.Mvc.Localization" />
<Reference Include="Microsoft.AspNetCore.Mvc.RazorPages" />
<Reference Include="Microsoft.AspNetCore.Mvc.TagHelpers" />

View File

@ -49,9 +49,6 @@ namespace Microsoft.Extensions.DependencyInjection
// +1 order
builder.AddDataAnnotations(); // +1 order
// +10 order
builder.AddJsonFormatters();
builder.AddCors();
return new MvcBuilder(builder.Services, builder.PartManager);

View File

@ -6,7 +6,7 @@
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc.ApiExplorer" />
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<ProjectReference Include="..\Microsoft.AspNetCore.Mvc.Core.TestCommon\Microsoft.AspNetCore.Mvc.Core.TestCommon.csproj" />
</ItemGroup>
</Project>

View File

@ -91,7 +91,7 @@ namespace Microsoft.AspNetCore.Mvc
{
var options = Options.Create(new MvcOptions());
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new JsonOutputFormatter(
options.Value.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings(),
ArrayPool<char>.Shared));

View File

@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
@ -106,7 +107,7 @@ namespace Microsoft.AspNetCore.Mvc
{
var options = Options.Create(new MvcOptions());
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new JsonOutputFormatter(
options.Value.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings(),
ArrayPool<char>.Shared));

View File

@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
@ -92,7 +93,7 @@ namespace Microsoft.AspNetCore.Mvc
{
var options = Options.Create(new MvcOptions());
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new JsonOutputFormatter(
options.Value.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings(),
ArrayPool<char>.Shared));

View File

@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.Logging.Abstractions;
@ -467,7 +468,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
// Set up default output formatters.
MvcOptions.OutputFormatters.Add(new HttpNoContentOutputFormatter());
MvcOptions.OutputFormatters.Add(new StringOutputFormatter());
MvcOptions.OutputFormatters.Add(new JsonOutputFormatter(
MvcOptions.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings(),
ArrayPool<char>.Shared));

View File

@ -8,6 +8,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
@ -71,7 +72,7 @@ namespace Microsoft.AspNetCore.Mvc
{
var options = Options.Create(new MvcOptions());
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new JsonOutputFormatter(
options.Value.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings(),
ArrayPool<char>.Shared));

View File

@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
@ -72,7 +73,7 @@ namespace Microsoft.AspNetCore.Mvc
{
var options = Options.Create(new MvcOptions());
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new JsonOutputFormatter(
options.Value.OutputFormatters.Add(new NewtonsoftJsonOutputFormatter(
new JsonSerializerSettings(),
ArrayPool<char>.Shared));

View File

@ -0,0 +1,32 @@
// 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.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Core
{
public class JsonResultTest
{
[Fact]
public async Task ExecuteResultAsync_ThrowsIfExecutorIsNotAvailableInServices()
{
// Arrange
var jsonResult = new JsonResult("Hello");
var message = "'JsonResult.ExecuteResultAsync' requires a reference to 'Microsoft.AspNetCore.Mvc.NewtonsoftJson'. " +
"Configure your application by adding a reference to the 'Microsoft.AspNetCore.Mvc.NewtonsoftJson' package and calling 'IMvcBuilder.AddNewtonsoftJson' " +
"inside the call to 'ConfigureServices(...)' in the application startup code.";
var actionContext = new ActionContext
{
HttpContext = new DefaultHttpContext { RequestServices = Mock.Of<IServiceProvider>() }
};
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => jsonResult.ExecuteResultAsync(actionContext));
Assert.Equal(message, ex.Message);
}
}
}

View File

@ -10,7 +10,7 @@
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<ProjectReference Include="..\Microsoft.AspNetCore.Mvc.Core.TestCommon\Microsoft.AspNetCore.Mvc.Core.TestCommon.csproj" />
<ProjectReference Include="..\Microsoft.AspNetCore.Mvc.TestDiagnosticListener\Microsoft.AspNetCore.Mvc.TestDiagnosticListener.csproj" />

View File

@ -10,6 +10,7 @@ using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Testing;
@ -711,12 +712,12 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
}
}
private class TestableJsonInputFormatter : JsonInputFormatter
private class TestableJsonInputFormatter : NewtonsoftJsonInputFormatter
{
private readonly bool _throwNonInputFormatterException;
public TestableJsonInputFormatter(bool throwNonInputFormatterException)
: base(GetLogger(), new JsonSerializerSettings(), ArrayPool<char>.Shared, new DefaultObjectPoolProvider(), new MvcOptions(), new MvcJsonOptions()
: base(GetLogger(), new JsonSerializerSettings(), ArrayPool<char>.Shared, new DefaultObjectPoolProvider(), new MvcOptions(), new MvcNewtonsoftJsonOptions()
{
// The tests that use this class rely on the 2.1 behavior of this formatter.
AllowInputFormatterExceptionMessages = true,
@ -781,12 +782,12 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
}
}
private class DerivedJsonInputFormatter : JsonInputFormatter
private class DerivedJsonInputFormatter : NewtonsoftJsonInputFormatter
{
private readonly bool _throwNonInputFormatterException;
public DerivedJsonInputFormatter(bool throwNonInputFormatterException)
: base(GetLogger(), new JsonSerializerSettings(), ArrayPool<char>.Shared, new DefaultObjectPoolProvider(), new MvcOptions(), new MvcJsonOptions()
: base(GetLogger(), new JsonSerializerSettings(), ArrayPool<char>.Shared, new DefaultObjectPoolProvider(), new MvcOptions(), new MvcNewtonsoftJsonOptions()
{
// The tests that use this class rely on the 2.1 behavior of this formatter.
AllowInputFormatterExceptionMessages = true,

View File

@ -10,6 +10,7 @@ using System.Text;
using System.Threading.Tasks;
using BasicWebSite.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
@ -53,7 +54,12 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.BadRequest);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType.MediaType);
var problemDetails = JsonConvert.DeserializeObject<ValidationProblemDetails>(await response.Content.ReadAsStringAsync());
var problemDetails = JsonConvert.DeserializeObject<ValidationProblemDetails>(
await response.Content.ReadAsStringAsync(),
new JsonSerializerSettings
{
Converters = { new ValidationProblemDetailsConverter() }
});
Assert.Collection(
problemDetails.Errors.OrderBy(kvp => kvp.Key),
kvp =>
@ -273,7 +279,12 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.NotFound);
var content = await response.Content.ReadAsStringAsync();
var problemDetails = JsonConvert.DeserializeObject<ProblemDetails>(content);
var problemDetails = JsonConvert.DeserializeObject<ProblemDetails>(
content,
new JsonSerializerSettings
{
Converters = { new ProblemDetailsConverter() }
});
Assert.Equal(404, problemDetails.Status);
Assert.Collection(
problemDetails.Extensions,
@ -328,7 +339,12 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.BadRequest);
var content = await response.Content.ReadAsStringAsync();
var validationProblemDetails = JsonConvert.DeserializeObject<ValidationProblemDetails>(content);
var validationProblemDetails = JsonConvert.DeserializeObject<ValidationProblemDetails>(
content,
new JsonSerializerSettings
{
Converters = { new ValidationProblemDetailsConverter() }
});
Assert.Equal("Error", validationProblemDetails.Title);
Assert.Equal(400, validationProblemDetails.Status);

View File

@ -575,7 +575,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
// Arrange
var type1 = typeof(ApiExplorerWebSite.Product).FullName;
var type2 = typeof(SerializableError).FullName;
var expectedMediaTypes = new[] { "application/json", "text/json", "application/xml", "text/xml" };
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
@ -592,13 +592,13 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
Assert.Equal(201, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
responseType = description.SupportedResponseTypes[1];
Assert.Equal(type2, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
}
[Fact]
@ -639,7 +639,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
// Arrange
var type1 = typeof(ApiExplorerWebSite.Product).FullName;
var type2 = typeof(SerializableError).FullName;
var expectedMediaTypes = new[] { "application/json", "text/json", "application/xml", "text/xml" };
var expectedMediaTypes = new[] { "application/json", "application/xml", "text/json", "text/xml" };
// Act
var response = await Client.GetAsync(
@ -656,13 +656,13 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
Assert.Equal(200, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
responseType = description.SupportedResponseTypes[1];
Assert.Equal(type2, responseType.ResponseType);
Assert.Equal(400, responseType.StatusCode);
Assert.Equal(
expectedMediaTypes,
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).ToArray());
responseType.ResponseFormats.Select(responseFormat => responseFormat.MediaType).OrderBy(o => o).ToArray());
}
[Fact]
@ -789,9 +789,9 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
Assert.Equal(typeof(XmlDataContractSerializerOutputFormatter).FullName, applicationXml.FormatterType);
var textJson = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "text/json");
Assert.Equal(typeof(JsonOutputFormatter).FullName, textJson.FormatterType);
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, textJson.FormatterType);
var applicationJson = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "application/json");
Assert.Equal(typeof(JsonOutputFormatter).FullName, applicationJson.FormatterType);
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, applicationJson.FormatterType);
}
[Fact]
@ -812,10 +812,10 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
var applicationJson = Assert.Single(
responseType.ResponseFormats,
format => format.MediaType == "application/json");
Assert.Equal(typeof(JsonOutputFormatter).FullName, applicationJson.FormatterType);
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, applicationJson.FormatterType);
var textJson = Assert.Single(responseType.ResponseFormats, f => f.MediaType == "text/json");
Assert.Equal(typeof(JsonOutputFormatter).FullName, textJson.FormatterType);
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, textJson.FormatterType);
}
[Fact]
@ -840,7 +840,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
responseFormat =>
{
Assert.Equal("application/hal+json", responseFormat.MediaType);
Assert.Equal(typeof(JsonOutputFormatter).FullName, responseFormat.FormatterType);
Assert.Equal(typeof(NewtonsoftJsonOutputFormatter).FullName, responseFormat.FormatterType);
});
}
@ -869,12 +869,12 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
[ConditionalTheory]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
[InlineData("Controller", "text/xml", "Microsoft.AspNetCore.Mvc.Formatters.XmlDataContractSerializerOutputFormatter")]
[InlineData("Action", "application/json", "Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter")]
[InlineData("Controller", "text/xml", typeof(XmlDataContractSerializerOutputFormatter))]
[InlineData("Action", "application/json", typeof(NewtonsoftJsonOutputFormatter))]
public async Task ApiExplorer_ResponseContentType_OverrideOnAction(
string action,
string contentType,
string formatterType)
Type formatterType)
{
// Arrange & Act
var response = await Client.GetAsync(
@ -889,7 +889,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
var responseType = Assert.Single(description.SupportedResponseTypes);
var responseFormat = Assert.Single(responseType.ResponseFormats);
Assert.Equal(contentType, responseFormat.MediaType);
Assert.Equal(formatterType, responseFormat.FormatterType);
Assert.Equal(formatterType.FullName, responseFormat.FormatterType);
}
[Fact]

View File

@ -280,7 +280,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, actualBody, ignoreLineEndingDifferences: true);
Assert.Equal(expectedBody, actualBody.Trim(), ignoreLineEndingDifferences: true);
}
[Fact]
@ -302,7 +302,7 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, actualBody, ignoreLineEndingDifferences: true);
Assert.Equal(expectedBody, actualBody.Trim(), ignoreLineEndingDifferences: true);
}
public static IEnumerable<object[]> HtmlHelperLinkGenerationData

View File

@ -8,6 +8,7 @@ using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Testing.xunit;
using Newtonsoft.Json;
using Xunit;

View File

@ -38,13 +38,13 @@ namespace Microsoft.AspNetCore.Mvc.FunctionalTests
var redirectResponse = await Client.PostAsync("TempDataProperty/CreateForView", content);
// Assert 1
Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode);
await redirectResponse.AssertStatusCodeAsync(HttpStatusCode.Redirect);
// Act 2
var response = await Client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), redirectResponse));
// Assert 2
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
await response.AssertStatusCodeAsync(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expected, body.ToString().Trim());
}

View File

@ -453,7 +453,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
});
// Override the AllowInputFormatterExceptionMessages setting ModelBindingTestHelper chooses.
var options = testContext.GetService<IOptions<MvcJsonOptions>>().Value;
var options = testContext.GetService<IOptions<MvcNewtonsoftJsonOptions>>().Value;
options.AllowInputFormatterExceptionMessages = false;
var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testContext.HttpContext.RequestServices);
@ -553,7 +553,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
});
// Override the AllowInputFormatterExceptionMessages setting ModelBindingTestHelper chooses.
var options = testContext.GetService<IOptions<MvcJsonOptions>>().Value;
var options = testContext.GetService<IOptions<MvcNewtonsoftJsonOptions>>().Value;
options.AllowInputFormatterExceptionMessages = false;
var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testContext.HttpContext.RequestServices);

View File

@ -6,6 +6,7 @@
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<ProjectReference Include="..\Microsoft.AspNetCore.Mvc.Core.TestCommon\Microsoft.AspNetCore.Mvc.Core.TestCommon.csproj" />
<Reference Include="Microsoft.Extensions.Logging" />

View File

@ -191,7 +191,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
serviceCollection.AddSingleton(Options.Create(mvcOptions));
}
serviceCollection.AddMvc();
serviceCollection.AddMvc()
.AddNewtonsoftJson();
serviceCollection
.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance)
.AddTransient<ILogger<DefaultAuthorizationService>, Logger<DefaultAuthorizationService>>();

View File

@ -5,7 +5,7 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Xunit;
@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
},
// Using a service type already in defaults.
ParameterType = typeof(JsonOutputFormatter)
ParameterType = typeof(ITypeActivatorCache)
};
var testContext = ModelBindingTestHelper.GetTestContext();
@ -43,8 +43,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.True(modelBindingResult.IsModelSet);
// Model
var outputFormatter = Assert.IsType<JsonOutputFormatter>(modelBindingResult.Model);
Assert.NotNull(outputFormatter);
var provider = Assert.IsAssignableFrom<ITypeActivatorCache>(modelBindingResult.Model);
Assert.NotNull(provider);
// ModelState
Assert.True(modelState.IsValid);
@ -65,7 +65,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
},
// Use a service type already in defaults.
ParameterType = typeof(JsonOutputFormatter),
ParameterType = typeof(ITypeActivatorCache),
};
var testContext = ModelBindingTestHelper.GetTestContext();
@ -79,8 +79,8 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.True(modelBindingResult.IsModelSet);
// Model
var outputFormatter = Assert.IsType<JsonOutputFormatter>(modelBindingResult.Model);
Assert.NotNull(outputFormatter);
var provider = Assert.IsAssignableFrom<ITypeActivatorCache>(modelBindingResult.Model);
Assert.NotNull(provider);
// ModelState
Assert.True(modelState.IsValid);
@ -101,7 +101,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
},
// Use a service type already in defaults.
ParameterType = typeof(IEnumerable<JsonOutputFormatter>),
ParameterType = typeof(IEnumerable<ITypeActivatorCache>),
};
var testContext = ModelBindingTestHelper.GetTestContext();
@ -115,7 +115,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
Assert.True(modelBindingResult.IsModelSet);
// Model
var formatterArray = Assert.IsType<JsonOutputFormatter[]>(modelBindingResult.Model);
var formatterArray = Assert.IsType<ITypeActivatorCache[]>(modelBindingResult.Model);
Assert.Single(formatterArray);
// ModelState
@ -186,7 +186,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
private class Person
{
public JsonOutputFormatter Service { get; set; }
public ITypeActivatorCache Service { get; set; }
}
// [FromServices] cannot be associated with a type. But a [FromServices] or [ModelBinder] subclass or custom
@ -240,7 +240,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
// Similar to a custom IBindingSourceMetadata implementation or [ModelBinder] subclass on a custom service.
var metadataProvider = new TestModelMetadataProvider();
metadataProvider
.ForType<JsonOutputFormatter>()
.ForType<ITypeActivatorCache>()
.BindingDetails(binding => binding.BindingSource = BindingSource.Services);
var testContext = ModelBindingTestHelper.GetTestContext(metadataProvider: metadataProvider);
@ -250,7 +250,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
{
Name = "parameter-name",
BindingInfo = bindingInfo,
ParameterType = typeof(JsonOutputFormatter),
ParameterType = typeof(ITypeActivatorCache),
};
// Act
@ -258,7 +258,7 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
// Assert
Assert.True(modelBindingResult.IsModelSet);
Assert.IsType<JsonOutputFormatter>(modelBindingResult.Model);
Assert.IsAssignableFrom<ITypeActivatorCache>(modelBindingResult.Model);
Assert.True(modelState.IsValid);
Assert.Empty(modelState);

View File

@ -36,11 +36,11 @@ namespace Microsoft.AspNetCore.Mvc.IntegrationTests
dataAnnotationOptionsSetup.Configure(Value);
var loggerFactory = new LoggerFactory();
var jsonOptions = Options.Create(new MvcJsonOptions());
var jsonOptions = Options.Create(new MvcNewtonsoftJsonOptions());
var charPool = ArrayPool<char>.Shared;
var objectPoolProvider = new DefaultObjectPoolProvider();
var mvcJsonMvcOptionsSetup = new MvcJsonMvcOptionsSetup(
var mvcJsonMvcOptionsSetup = new NewtonosftJsonMvcOptionsSetup(
loggerFactory,
jsonOptions,
charPool,

View File

@ -5,9 +5,9 @@ using System;
using System.Collections.Generic;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
public class TempDataSerializerTest
public class BsonTempDataSerializerTest
{
public static TheoryData<object, Type> InvalidTypes
{
@ -29,14 +29,14 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
public void EnsureObjectCanBeSerialized_ThrowsException_OnInvalidType(object value, Type type)
{
// Arrange
var testProvider = new TempDataSerializer();
var testProvider = new BsonTempDataSerializer();
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() =>
{
testProvider.EnsureObjectCanBeSerialized(value);
});
Assert.Equal($"The '{typeof(TempDataSerializer).FullName}' cannot serialize " +
Assert.Equal($"The '{typeof(BsonTempDataSerializer).FullName}' cannot serialize " +
$"an object of type '{type}'.",
exception.Message);
}
@ -60,14 +60,14 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
public void EnsureObjectCanBeSerialized_ThrowsException_OnInvalidDictionaryType(object value, Type type)
{
// Arrange
var testProvider = new TempDataSerializer();
var testProvider = new BsonTempDataSerializer();
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(() =>
{
testProvider.EnsureObjectCanBeSerialized(value);
});
Assert.Equal($"The '{typeof(TempDataSerializer).FullName}' cannot serialize a dictionary " +
Assert.Equal($"The '{typeof(BsonTempDataSerializer).FullName}' cannot serialize a dictionary " +
$"with a key of type '{type}'. The key must be of type 'System.String'.",
exception.Message);
}
@ -98,7 +98,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
public void EnsureObjectCanBeSerialized_DoesNotThrow_OnValidType(object value)
{
// Arrange
var testProvider = new TempDataSerializer();
var testProvider = new BsonTempDataSerializer();
// Act & Assert (Does not throw)
testProvider.EnsureObjectCanBeSerialized(value);
@ -108,7 +108,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
public void DeserializeTempData_ReturnsEmptyDictionary_DataIsEmpty()
{
// Arrange
var serializer = new TempDataSerializer();
var serializer = new BsonTempDataSerializer();
// Act
var tempDataDictionary = serializer.Deserialize(new byte[0]);
@ -123,7 +123,7 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Filters
{
// Arrange
var key = "NullKey";
var testProvider = new TempDataSerializer();
var testProvider = new BsonTempDataSerializer();
var input = new Dictionary<string, object>
{
{ key, null }

View File

@ -4,21 +4,20 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Formatters.Json;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
{
public class MvcJsonOptionsExtensionsTests
public class MvcNewtonsoftJsonOptionsExtensionsTest
{
[Fact]
public void UseCamelCasing_WillSet_CamelCasingStrategy_NameStrategy()
{
// Arrange
var options = new MvcJsonOptions();
var options = new MvcNewtonsoftJsonOptions();
options.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
NamingStrategy = new DefaultNamingStrategy()
@ -162,7 +161,7 @@ namespace Microsoft.Extensions.DependencyInjection
public void UseMemberCasing_WillSet_DefaultNamingStrategy_AsNamingStrategy()
{
// Arrange
var options = new MvcJsonOptions();
var options = new MvcNewtonsoftJsonOptions();
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
@ -217,7 +216,7 @@ namespace Microsoft.Extensions.DependencyInjection
public void UseCamelCasing_WillThrow_IfContractResolver_IsNot_DefaultContractResolver()
{
// Arrange
var options = new MvcJsonOptions();
var options = new MvcNewtonsoftJsonOptions();
options.SerializerSettings.ContractResolver = new FooContractResolver();
var expectedMessage = Resources.FormatInvalidContractResolverForJsonCasingConfiguration(nameof(FooContractResolver), nameof(DefaultContractResolver));
@ -231,7 +230,7 @@ namespace Microsoft.Extensions.DependencyInjection
public void UseMemberCasing_WillThrow_IfContractResolver_IsNot_DefaultContractResolver()
{
// Arrange
var options = new MvcJsonOptions();
var options = new MvcNewtonsoftJsonOptions();
options.SerializerSettings.ContractResolver = new FooContractResolver();
var expectedMessage = Resources.FormatInvalidContractResolverForJsonCasingConfiguration(nameof(FooContractResolver), nameof(DefaultContractResolver));
@ -243,14 +242,14 @@ namespace Microsoft.Extensions.DependencyInjection
// NOTE: This method was created to make sure to create a different instance of contract resolver as by default
// MvcJsonOptions uses a static shared instance of resolver which when changed causes other tests to fail.
private MvcJsonOptions CreateDefaultMvcJsonOptions()
private MvcNewtonsoftJsonOptions CreateDefaultMvcJsonOptions()
{
var options = new MvcJsonOptions();
var options = new MvcNewtonsoftJsonOptions();
options.SerializerSettings.ContractResolver = JsonSerializerSettingsProvider.CreateContractResolver();
return options;
}
private static string SerializeToJson(MvcJsonOptions options, object value)
private static string SerializeToJson(MvcNewtonsoftJsonOptions options, object value)
{
return JsonConvert.SerializeObject(
value: value,

View File

@ -0,0 +1,30 @@
// 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 Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
{
public class NewtonsoftJsonMvcBuilderExtensionsTest
{
[Fact]
public void AddNewtonsoftJson_ConfiguresOptions()
{
// Arrange
var services = new ServiceCollection();
// Act
services.AddMvc()
.AddNewtonsoftJson((options) =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
// Assert
Assert.Single(services, d => d.ServiceType == typeof(IConfigureOptions<MvcNewtonsoftJsonOptions>));
}
}
}

View File

@ -0,0 +1,63 @@
// 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 Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.NewtonsoftJson;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
{
public class NewtonsoftJsonMvcCoreBuilderExtensionsTest
{
[Fact]
public void AddNewtonsoftJson_ConfiguresOptions()
{
// Arrange
var services = new ServiceCollection();
// Act
services.AddMvcCore()
.AddNewtonsoftJson((options) =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
// Assert
Assert.Single(services, d => d.ServiceType == typeof(IConfigureOptions<MvcNewtonsoftJsonOptions>));
}
[Fact]
public void AddServicesCore_ReplacesDefaultJsonHelper()
{
// Arrange
var services = new ServiceCollection()
.AddSingleton<IJsonHelper, DefaultJsonHelper>();
// Act
NewtonsoftJsonMvcCoreBuilderExtensions.AddServicesCore(services);
// Assert
var jsonHelper = Assert.Single(services, d => d.ServiceType == typeof(IJsonHelper));
Assert.Same(typeof(NewtonsoftJsonHelper), jsonHelper.ImplementationType);
}
[Fact]
public void AddServicesCore_ReplacesDefaultTempDataSerializer()
{
// Arrange
var services = new ServiceCollection()
.AddSingleton<TempDataSerializer, DefaultTempDataSerializer>();
// Act
NewtonsoftJsonMvcCoreBuilderExtensions.AddServicesCore(services);
// Assert
var tempDataSerializer = Assert.Single(services, d => d.ServiceType == typeof(TempDataSerializer));
Assert.Same(typeof(BsonTempDataSerializer), tempDataSerializer.ImplementationType);
}
}
}

View File

@ -8,7 +8,7 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
public class JsonHelperTest
{
@ -20,8 +20,8 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
};
var helper = new JsonHelper(
new JsonOutputFormatter(settings, ArrayPool<char>.Shared),
var helper = new NewtonsoftJsonHelper(
new NewtonsoftJsonOutputFormatter(settings, ArrayPool<char>.Shared),
ArrayPool<char>.Shared);
var obj = new
{
@ -48,8 +48,8 @@ namespace Microsoft.AspNetCore.Mvc.ViewFeatures
NamingStrategy = new CamelCaseNamingStrategy(),
},
};
var helper = new JsonHelper(
new JsonOutputFormatter(settings, ArrayPool<char>.Shared),
var helper = new NewtonsoftJsonHelper(
new NewtonsoftJsonOutputFormatter(settings, ArrayPool<char>.Shared),
ArrayPool<char>.Shared);
var obj = new
{

View File

@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters.Json
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
public class JsonPatchOperationsArrayProviderTests
{

View File

@ -19,7 +19,7 @@ using Moq;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
public class JsonResultExecutorTest
{
@ -284,7 +284,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
return new JsonResultExecutor(
new TestHttpResponseStreamWriterFactory(),
logger ?? NullLogger<JsonResultExecutor>.Instance,
Options.Create(new MvcJsonOptions()),
Options.Create(new MvcNewtonsoftJsonOptions()),
ArrayPool<char>.Shared);
}

View File

@ -7,7 +7,7 @@ using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
@ -15,7 +15,7 @@ using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Xunit;
namespace Microsoft.AspNetCore.Mvc
namespace Microsoft.AspNetCore.Mvc.NewtonsoftJson
{
public class JsonResultTest
{
@ -47,11 +47,11 @@ namespace Microsoft.AspNetCore.Mvc
var executor = new JsonResultExecutor(
new TestHttpResponseStreamWriterFactory(),
NullLogger<JsonResultExecutor>.Instance,
Options.Create(new MvcJsonOptions()),
Options.Create(new MvcNewtonsoftJsonOptions()),
ArrayPool<char>.Shared);
var services = new ServiceCollection();
services.AddSingleton(executor);
services.AddSingleton<IActionResultExecutor<JsonResult>>(executor);
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;

View File

@ -5,7 +5,8 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" />
<Reference Include="Microsoft.AspNetCore.Mvc" />
<Reference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" />
<ProjectReference Include="..\Microsoft.AspNetCore.Mvc.Core.TestCommon\Microsoft.AspNetCore.Mvc.Core.TestCommon.csproj" />
</ItemGroup>

View File

@ -21,7 +21,7 @@ using Xunit;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
public class JsonInputFormatterTest
public class NewtonsoftJsonInputFormatterTest
{
private static readonly ObjectPoolProvider _objectPoolProvider = new DefaultObjectPoolProvider();
private static readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings();
@ -31,7 +31,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{
// Arrange
#pragma warning disable CS0618
var formatter = new JsonInputFormatter(
var formatter = new NewtonsoftJsonInputFormatter(
GetLogger(),
_serializerSettings,
ArrayPool<char>.Shared,
@ -74,13 +74,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
public async Task Version_2_1_Constructor_BuffersRequestBody_UsingDefaultOptions()
{
// Arrange
var formatter = new JsonInputFormatter(
var formatter = new NewtonsoftJsonInputFormatter(
GetLogger(),
_serializerSettings,
ArrayPool<char>.Shared,
_objectPoolProvider,
new MvcOptions(),
new MvcJsonOptions());
new MvcNewtonsoftJsonOptions());
var content = "{name: 'Person Name', Age: '30'}";
var contentBytes = Encoding.UTF8.GetBytes(content);
@ -119,7 +119,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{
// Arrange
#pragma warning disable CS0618
var formatter = new JsonInputFormatter(
var formatter = new NewtonsoftJsonInputFormatter(
GetLogger(),
_serializerSettings,
ArrayPool<char>.Shared,
@ -162,13 +162,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{
SuppressInputFormatterBuffering = true,
};
var formatter = new JsonInputFormatter(
var formatter = new NewtonsoftJsonInputFormatter(
GetLogger(),
_serializerSettings,
ArrayPool<char>.Shared,
_objectPoolProvider,
mvcOptions,
new MvcJsonOptions());
new MvcNewtonsoftJsonOptions());
var content = "{name: 'Person Name', Age: '30'}";
var contentBytes = Encoding.UTF8.GetBytes(content);
@ -205,13 +205,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
{
SuppressInputFormatterBuffering = false,
};
var formatter = new JsonInputFormatter(
var formatter = new NewtonsoftJsonInputFormatter(
GetLogger(),
_serializerSettings,
ArrayPool<char>.Shared,
_objectPoolProvider,
mvcOptions,
new MvcJsonOptions());
new MvcNewtonsoftJsonOptions());
var content = "{name: 'Person Name', Age: '30'}";
var contentBytes = Encoding.UTF8.GetBytes(content);
@ -570,7 +570,7 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
[InlineData("{", "", "Unexpected end when reading JSON. Path '', line 1, position 1.")]
[InlineData("{\"a\":{\"b\"}}", "a", "Invalid character after parsing property name. Expected ':' but got: }. Path 'a', line 1, position 9.")]
[InlineData("{\"age\":\"x\"}", "age", "Could not convert string to decimal: x. Path 'age', line 1, position 10.")]
[InlineData("{\"login\":1}", "login", "Error converting value 1 to type 'Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatterTest+UserLogin'. Path 'login', line 1, position 10.")]
[InlineData("{\"login\":1}", "login", "Error converting value 1 to type 'Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonInputFormatterTest+UserLogin'. Path 'login', line 1, position 10.")]
[InlineData("{\"login\":{\"username\":\"somevalue\"}}", "login.Password", "Required property 'Password' not found in JSON. Path 'login', line 1, position 33.")]
public async Task ReadAsync_WithAllowInputFormatterExceptionMessages_RegistersJsonInputExceptionsAsInputFormatterException(
string content,
@ -624,13 +624,13 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
public async Task ReadAsync_AllowInputFormatterExceptionMessages_DoesNotWrapJsonInputExceptions()
{
// Arrange
var formatter = new JsonInputFormatter(
var formatter = new NewtonsoftJsonInputFormatter(
GetLogger(),
_serializerSettings,
ArrayPool<char>.Shared,
_objectPoolProvider,
new MvcOptions(),
new MvcJsonOptions()
new MvcNewtonsoftJsonOptions()
{
AllowInputFormatterExceptionMessages = true,
});
@ -653,10 +653,10 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
Assert.NotEmpty(modelError.ErrorMessage);
}
private class TestableJsonInputFormatter : JsonInputFormatter
private class TestableJsonInputFormatter : NewtonsoftJsonInputFormatter
{
public TestableJsonInputFormatter(JsonSerializerSettings settings)
: base(GetLogger(), settings, ArrayPool<char>.Shared, _objectPoolProvider, new MvcOptions(), new MvcJsonOptions())
: base(GetLogger(), settings, ArrayPool<char>.Shared, _objectPoolProvider, new MvcOptions(), new MvcNewtonsoftJsonOptions())
{
}
@ -670,15 +670,15 @@ namespace Microsoft.AspNetCore.Mvc.Formatters
return NullLogger.Instance;
}
private JsonInputFormatter CreateFormatter(JsonSerializerSettings serializerSettings = null, bool allowInputFormatterExceptionMessages = false)
private NewtonsoftJsonInputFormatter CreateFormatter(JsonSerializerSettings serializerSettings = null, bool allowInputFormatterExceptionMessages = false)
{
return new JsonInputFormatter(
return new NewtonsoftJsonInputFormatter(
GetLogger(),
serializerSettings ?? _serializerSettings,
ArrayPool<char>.Shared,
_objectPoolProvider,
new MvcOptions(),
new MvcJsonOptions()
new MvcNewtonsoftJsonOptions()
{
AllowInputFormatterExceptionMessages = allowInputFormatterExceptionMessages,
});

Some files were not shown because too many files have changed in this diff Show More