XmlSerializerInputFormatter deprecated, what's the replacement? [duplicate] - c#

I am using the following to accept XML serialized in my Core API App.
services.AddMvc(options =>
{
// allow xml format for input
options.InputFormatters.Add(new XmlSerializerInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
After updating to ASP.NET Core 2.1 I receive the following warning:
'XmlSerializerInputFormatter.XmlSerializerInputFormatter()' is obsolete: 'This constructor is obsolete and will be removed in a future version.'
What is the new way to handle this?

According to the source code, there's a constructor that has not been marked as Obsolete:
public XmlSerializerInputFormatter(MvcOptions options)
This constructor takes an instance of MvcOptions, so you can pass through your existing options argument:
services.AddMvc(options =>
{
// allow xml format for input
options.InputFormatters.Add(new XmlSerializerInputFormatter(options));
}) ...
As of ASP.NET Core 3.0, this constructor is the only one available. Those that were marked obsolete have now been removed.

With .NET Core 2.2 or later XmlSerializerInputFormatter should be marked as deprecated.
Instead a of explicitly defining XML serializers as we did before, in the .NET Core 2.2 we can add them simply by calling AddXmlSerializerFormatters() method which will do the job now. Read here why it has been deprecated
Here is how you can do it.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(config =>
{
config.RespectBrowserAcceptHeader = true;
config.ReturnHttpNotAcceptable = true;
config.OutputFormatters.Add(new CsvOutputFormatter());
}).AddXmlSerializerFormatters().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

Related

I set default JsonSerializer to Utf8Json

Using c# 8 and .netcore 3.1.
I've read HERE that Utf8Json library process json serialization and deserialization faster that NewtonsoftJson.
We've recently upgraded our servers code from .netcore 2.2 to 3.1 mostly for performance improvements.
Thus, it is reasonable that we also use the best serialization library.
So my questions are:
In Startup.cs there is this
services.AddControllers().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
And I want it to use a different library, so I found out that I can use .AddJsonOptions but I cannot figure out how to set default serializer, even after using my google-fu skills.
Since I've been using [JsonProperty("<name>")] everywhere in my code in order to reduce json string size, do I need to format everything for the new serializer or is there a way to make him consider the property attribute ? (attribute is Newtonsoft)
Thanks.
#Ori you can use Utf8json in net core 3.1 projects.
Use
[DataMember(Name = "RoleType")]
public string Role_Type { get; set; }
Instead of
[JsonProperty("<name>")]
To use Utf8json formatters in Asp.Net core you need add the formatters as mentioned below.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews()
// Add Utf8Json formatters
.AddMvcOptions(option =>
{
option.OutputFormatters.Clear();
option.OutputFormatters.Add(new JsonOutputFormatter (StandardResolver.Default));
option.InputFormatters.Clear();
option.InputFormatters.Add(new JsonInputFormatter ());
});
}
You can also refer below link for the formatters.
https://github.com/neuecc/Utf8Json/blob/master/src/Utf8Json.AspNetCoreMvcFormatter/Formatter.cs
I am using utf8json and its working great for us.

React.NET .NET Core 3.1 Not passing props into component

I am using MVC ASP.NET Core 3.1 and React.NET and I am getting this issue.
When I render my component, the component renders, but the props are always null. It is almost as if the Html.React render method isn't properly passing the values over, please help!
I'm only going to add relevent code to the react (my startup.cs has more settings)
Startup.cs
public void ConfigureServices(IServiceCollection services) {
services.AddJsEngineSwitcher(options => options.DefaultEngineName = ChakraCoreJsEngine.EngineName).AddChakraCore();
services.AddReact();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseReact(config =>
{
// If you want to use server-side rendering of React components,
// add all the necessary JavaScript files here. This includes
// your components as well as all of their dependencies.
// See http://reactjs.net/ for more information. Example:
config
.AddScript("~/scripts/react_common/login.jsx");
config.SetLoadBabel(true);
});
}
index.cshtml (or any view, just trying to use this HTML extension helper)
#Html.React("Login", new
{
Test = "Test"
}, serverOnly: true)
login.jsx
class Login extends React.Component {
render() {
return <div>{this.props.Test}</div>
}
No matter what I do, it will never display "Test" for example. I need to know why it isn't passing the values into the props. I am starting to lose my mind over this problem, it worked just fine before I started migrating to .NET Core.
More details (Nuget Packages)
React.Asp.Net(5.1.2)
React.AspNet.Middleware(5.1.2)
Please help.
The default JSON serializer contract resolver is set to automatically convert it into camelCase (React). You have to over-ride this behavior if you want it to maintain the supplied case - in the Configure method in startup.cs:
app.UseReact(...
app.UseStaticFiles();
//Ensure to place this after the UseRact statement above
ReactSiteConfiguration.Configuration.JsonSerializerSettings.ContractResolver = new DefaultContractResolver();
Hopefully this helps someone else from going crazy

How to prevent json results in MVC .net core to lowercase first letter of model properties [duplicate]

I've just swapped our project from ASP .Net Core 1.0.0-rc2-final to 1.0.0. Our website and client have stopped working because of the capitalization of JSON properties. For example, this line of JavaScript now fails
for (var i = 0; i < collection.Items.length; i++){
because the controller now calls the array "items" instead of "Items". I have made no changes beyond installing the updated packages and editing the project.json file. I have not changed the C# model files which still capitalize their properties.
Why have the ASP.Net Core controllers started returning JSON with lower-cased properties? How do I go back to them honoring the case of the property names from the model?
MVC now serializes JSON with camel case names by default
Use this code to avoid camel case names by default
services.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
Source:
https://github.com/aspnet/Announcements/issues/194
In case you found this from Google and looking for a solution for Core 3.
Core 3 uses System.Text.Json, which by default does not preserve the case. As mentioned with this GitHub issue, setting the PropertyNamingPolicy to null will fix the problem.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllers()
.AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
and if you don't want to change the global settings, for one action only it's like this:
return Json(obj, new JsonSerializerOptions { PropertyNamingPolicy = null });
You can change the behavior like this:
services
.AddMvc()
.AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
See the announcement here: https://github.com/aspnet/Announcements/issues/194
For those who migrated to Core 3.1 and have Core MVC project can use following setup code in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllersWithViews().AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null);
...
}
This will fix it in dotnet core 3 webapi, so that it doesn't change your property names at all, and you return to your client exactly what you intended to.
In Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
services.AddHttpClient();
}
For someone who does not want to set it globally, it is possible to use ContractResolver also to return as Json result:
public IActionResult MyMethod()
{
var obj = new {myValue = 1};
return Json(obj, new JsonSerializerSettings {ContractResolver = new DefaultContractResolver()});
}
For some one who is using ASP.net WEB API ( rather than ASP.NET Core).
Add this line in your WebApiConfig.
//Comment this jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();
Adding this as an answer here because this comes up first in google search for web api as well.
For ASP MVC Core 6 Web API , Add below code into Program.cs file will make sure JSON propreties name follow C# model properties name in right casing. No 3rd party package require
using Microsoft.AspNetCore.Mvc;
builder.Services.Configure<JsonOptions>(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
For Core 2.x versions, using this code you can avoid camel case names by default. You need to add following code inside the ConfigureServices method of Startup.cs file.
services.AddMvc()
.AddJsonOptions(o =>
{
if (o.SerializerSettings.ContractResolver != null)
{
var castedResolver = o.SerializerSettings.ContractResolver
as DefaultContractResolver;
castedResolver.NamingStrategy = null;
}
});
Recently had this issue with .Net6
The solution turned out to be that I needed to install
Microsoft.AspNetCore.Mvc.NewtonsoftJson 6.0.0.x (Note, use 7.x for .Net 7)
Found this out from Mason's post:
Microsoft.AspNetCore.Mvc.NewtonsoftJson 6.0.2 is not compatible with net5.0
Install
Microsoft.AspNetCore.Mvc.NewtonsoftJson
For .net 6 you should select this version: 6.0.13
and then go to Program.cs and configure it like this
builder.Services
.AddControllersWithViews()
.AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

How do I change the ILazyLoader implementation in Entity Framework Core 2.2?

I created an ASP.NET Core 2.2 Application, in Startup.cs I have this:
services.AddEntityFrameworkSqlServer();
services.AddScoped<ILazyLoader, MyLazyLoader>();
services.AddDbContext<ModelContext>(builder =>
{
builder.UseLazyLoadingProxies();
builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
var options = builder.Options;
services.AddSingleton(options);
});
But the lazyloader is not changed, what do I need to change do make this change?
Remove the first two lines
services.AddEntityFrameworkSqlServer();
services.AddScoped<ILazyLoader, MyLazyLoader>();
and setup the EFC related stuff inside AddDbContext builder action.
builder.UseSqlServer will do internally AddEntityFrameworkSqlServer(), and to replace the ILazyLoader service, use - well, ReplaceService method:
services.AddDbContext<ModelContext>(builder =>
{
builder.ReplaceService<ILazyLoader, MyLazyLoader>();
// ...
});

ASP.NET Core 1.0 upgrade to ASP.NET Core 2.0 Upgrade Authentication in ConfigureServices - How do I use Fields in Core 2.0?

I'm working with code that has worked and need migrate from Core 1.0 to Core 2.0 and need to use and migrate Fields in the Services Authentication. How do I use Fields in Core 2.0? (I reviewed the Migration document at Microsoft too, but cannot find anything.) https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
public void ConfigureServices(IServiceCollection services)
and I'm having trouble with the following: (How do I add the following in Core 2.0)
Fields = { "email", "last_name", "first_name" },
Here's my code below.
ASP.NET Core 1.0
app.UseFacebookAuthentication(new FacebookOptions
{
AppId = Configuration["Authentication:Test:Facebook:AppId"],
AppSecret = Configuration["Authentication:Test:Facebook:AppSecret"],
Fields = { "email", "last_name", "first_name" },
});
Need to Migrate to ASP.NET Core 2.0
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Test:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Test:Facebook:AppSecret"];
});
Fields is read-only, but you can modify its contents. Taking your example, a code-level migration might look like this:
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Test:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Test:Facebook:AppSecret"];
facebookOptions.Fields.Clear();
facebookOptions.Fields.Add("email");
facebookOptions.Fields.Add("last_name");
facebookOptions.Fields.Add("first_name");
});
However, this is not actually necessary as these are set by default. See the code snippet from the source:
public FacebookOptions()
{
// ...
Fields.Add("name");
Fields.Add("email");
Fields.Add("first_name");
Fields.Add("last_name");
// ...
}
It looks like it wasn’t necessary even in the previous version of ASP.NET Core, but your code would work fine as you were just replacing the defaults (without name). If you really don’t want to request the name, you can use facebookOptions.Fields.Remove(“name”).

Categories