I can't use ContractResolver in net core 3 startap - .net-core-3.0

I've tried:
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()
but net core 3 startup don't support this assign

.Net core uses System.Text.Json now but you can still use Newtonsoft if you want to.
In your startup.cs file add the following in ConfigureServices method.
services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new JsonCustomContractResolver();
});
That should do it

Related

Where add custom binding in .net core?

I'm new in .net core, and I have custom binding for MTOM as below:
MtomMessageEncodingBindingElement encoding = new MtomMessageEncodingBindingElement();
var transport = new HttpTransportBindingElement();
transport.TransferMode = (CoreWCF.TransferMode)TransferMode.Streamed;
var binding = new CustomBinding(encoding, transport);
I need to add it on WCF service in .net core, My program.cs as below:
static void Main(string[] args)
{
IWebHost host = CreateWebHostBuilder(args).Build();
host.Run();
}
where I can add binding exactly ? I try to add it in startup file. but I do not know how.

Automapper.Initialize method not found

I'm creating simple MVC app where I want to use Automapper.
I've installed in my project, configure profile like this :
public class ExportProfile : Profile
{
public ExportProfile()
{
CreateMap<User, UserDto>().ReverseMap();
CreateMap<Export, ExportDto>().ReverseMap();
CreateMap<Local, LocalDto>().ReverseMap();
}
}
Then I'd like to go to: Global.asax
Mapper.Initialize( x => x.AddProfile<ExportProfile>() );
And then I get: 'Mapper' does not contain a definition for 'Initialize'
What am I doing wrong?
In .NET core you can use the following Extension in startup to configure Automapper Services use NuGet package:
AutoMapper.Extensions.Microsoft.DependencyInjection
Registration Code
services.AddAutoMapper(typeof(EntityToViewModelProfile).Assembly);
As far as I can see you are not using .NET core, because you have Global.asax file. So you can either check the above extension method content by following the link:
https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/master/src/AutoMapper.Extensions.Microsoft.DependencyInjection/ServiceCollectionExtensions.cs
Or you can use the following configuration:
var configuration = new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(EntityToViewModelProfile).Assembly);
});
And resolve IMapper interface based on IOC container you are using with the following instantiation method:
IMapper mapper = configuration.CreateMapper();
Here is an example of this type configuration using Autofac:
builder.Register<IConfigurationProvider>(c => new MapperConfiguration(cfg =>
{
cfg.AddMaps(typeof(EntityToViewModelProfile).Assembly);
})).SingleInstance();
builder.Register(c => c.Resolve<IConfigurationProvider>().CreateMapper()).InstancePerLifetimeScope();
Mapper.Initialize( x => x.AddProfile<ExportProfile>() ) is obsolete.
You can use the Mapper directly into your controller class like I did here:
var config = new MapperConfiguration(cfg => cfg.CreateMap<Customer,CustomerDTO>());
var mapper = config.CreateMapper();
return context.Customers.ToList().Select(mapper.Map<Customer, CustomerDTO>);

Resolving Authentication services in .Net Core 2.0 with AutoFac

I'm in the process of migrating a .Net Core 1.x project to .Net Core 2.0. One of the things that has changed is that Authentication is now configured in ConfigureServices during startup using extensions to IServiceCollection.
I have some custom services which are used in my authentication schemes, however the bulk of the DI registration is built using AutoFac (after this is called):
public IServiceProvider ConfigureServices(IServiceCollection services)
{
//Other .Net Services Registered
services.AddTransient<ITicketStore, DistributedCacheTicketStore>();
services.AddSingleton<AuthenticationEvents>();
var sp = services.BuildServiceProvider();
services.AddAuthentication()
.AddCookie(options =>
{
//Other cookie options
options.SessionStore = sp.GetService<ITicketStore>();
})
.AddOpenIdConnect(options =>
{
//Other OIDC options
options.Events = sp.GetService<AuthenticationEvents>();
});
//Register application services with AutoFac
var builder = new ContainerBuilder();
RegisterAutoFacTypes(builder);
//Include services from .Net DI container
builder.Populate(services);
//Build and return the AutoFac container
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
At the moment, I'm attempting to also register the dependencies of DistributedCacheTicketStore and AuthenticationEvents on the IServiceCollection to allow me to use them in my Authentication config, but this is getting messy and I'd much rather keep it in the AutoFac registration.
Is there a sensible way of refactoring this to keep these registrations in AutoFac, but still use services.AddAuthentication() before the AutoFac container is built?

IdentityManager with VNext

Has anyone tried using IdentityManager with vNext?
I'm having problems with the app.UseIdentityManager(IdentityManagerOptions) extension method.
It doesn't exist.
So I tried using the extension method made for UseIdentityServer (found here) by changing all the server related aspects to manager.
When I do that, I get the System.NullReferenceException in line 43.
Any kind of advice on how to go about with the extension method will be really appreciated
I am using ASPNET 5 beta6 and I got this to work.
Try using this updated IApplicationBuilder extension found in the Samples repo on dev branch. Repurpose the method to accept IdentityManagerOptions rather than IdentityServerOptions and edit the builder to UseIdentityManager
In short here is what my extension method looks like
public static class IApplicationBuilderExtensions
{
public static void UseIdentityManager(this IApplicationBuilder app, IdentityManagerOptions options)
{
app.UseOwin(addToPipeline =>
{
addToPipeline(next =>
{
var builder = new AppBuilder();
var provider = app.ApplicationServices.GetService<IDataProtectionProvider>();
builder.Properties["security.DataProtectionProvider"] =
new DataProtectionProviderDelegate(purposes =>
{
var dataProtection = provider.CreateProtector(string.Join(",", purposes));
return new DataProtectionTuple(dataProtection.Protect, dataProtection.Unprotect);
});
builder.UseIdentityManager(options);
var appFunc =
builder.Build(typeof (Func<IDictionary<string, object>, Task>)) as
Func<IDictionary<string, object>, Task>;
return appFunc;
});
});
}
}
I'm using vNext and I've noticed that many things have changed and will continue to change.
For my own needs I've been able to get identity up and running fairly easily and there are two steps that I've had to take to get it running properly. What I've done should work for you as well.
In your StartUp.cs you will need to make sure you add the following to the ConfigureServices method:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
In addition to that you will need to configure your app to use identity and to do this you need to do the following in your Configure() method:
app.UseIdentity();

How to plug my Autofac container into ASP. NET Identity 2.1

I have been looking into the new features of the new version of ASP.NET Identity 2.1 and one of its enhancements is the new IoC features integrated into the OWIN Middleware.
One of the sentences that I looked in the examples is this one:
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
This sentence receives a function delegate which returns a new instance of a manager implementation provided on the examples:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
I personally dont like this implementation because I am not able to use a container to inject any dependency that I want for these managers.
Also there is an "IdentityFactoryOptions" and a "IOwinContext" that are "magically" injected to the function which Im not able to pull out into my IoC container.
Do anyone have a better workaround on this implementation?
I'm starting from an out-of-the-box MVC5 installation and using AutoFac as an IoC container. It sounds like I am trying to acheive a similar goal as you, so let me explain what I've done. As a disclaimer, I am fairly new to using IoC and to Identity.
I believe the IOwinContext is unnecessary in a role as an IoC if you are using your own - I switched over to registering my ApplicationUserManager with AutoFac. To achieve this I had to:
Remove CreatePerOwinContext lines from Startup.Auth since I'll register ApplicationDbContext and ApplicationUserManager in AutoFac.
//app.CreatePerOwinContext(ApplicationDbContext.Create);
//app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
Modify the ApplicationUserManager constructor arguments and included everything from the Create function.
public ApplicationUserManager(IUserStore<ApplicationUser> store, IdentityFactoryOptions<ApplicationUserManager> options)
: base(store)
{
//all the code from the 'Create' function here, using `this` for `manager`
}
Set the AccountController to have a single constructor taking an ApplicationUserManager as an argument and scrapped the UserManager property that grabs the ApplicationUserManager from the OwinContext.
private ApplicationUserManager _userManager; //every thing that needs the old UserManager property references this now
public AccountController(ApplicationUserManager userManager)
{
_userManager = userManager;
}
Register everything with AutoFac, including an instance of IdentityFactoryOptions.
var x = new ApplicationDbContext();
builder.Register<ApplicationDbContext>(c => x);
builder.Register<UserStore<ApplicationUser>>(c => new UserStore<ApplicationUser>(x)).AsImplementedInterfaces();
builder.Register<IdentityFactoryOptions<ApplicationUserManager>>(c => new IdentityFactoryOptions<ApplicationUserManager>()
{
DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ApplicationName")
});
builder.RegisterType<ApplicationUserManager>();
That's the rough summary. I may have missed a couple of other tweaks I had to do along the way.
Ben's answer gets the general idea right, but it manually instantiates the DbContext and uses this instance when registering the rest of the types. IMO, that's a bad idea (one shouldn't use the same eternal db context for ALL requests).
Derek's comment is a big improvement, but it doesn't pass the database context to the user store, resulting in errors such as "The entity type ApplicationUser is not part of the model for the current context.".
I've included my code below, for reference - it's really similar to Derek's.
builder.RegisterType<MyApplicationContext>().AsSelf().InstancePerRequest()
//...
builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
builder.RegisterType<ApplicationSignInManager>().AsSelf().InstancePerRequest();
builder.Register(c => new UserStore<ApplicationUser>(c.Resolve<MyApplicationContext>())).AsImplementedInterfaces().InstancePerRequest();
builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).As<IAuthenticationManager>();
builder.Register(c => new IdentityFactoryOptions<ApplicationUserManager>
{
DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("Application​")
});
For reference here's how you can wire everything up using Unity:
var container = new UnityContainer();
container.RegisterType<MyDbContext>(new InjectionConstructor("ConnectionStringName"));
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
new InjectionConstructor(typeof(MyDbContext)));
container.RegisterType<IRoleStore<IdentityRole, string>, RoleStore<IdentityRole>>(
new InjectionConstructor(typeof(MyDbContext)));
container.RegisterType<IdentityFactoryOptions<ApplicationUserManager>>(new InjectionFactory(x =>
new IdentityFactoryOptions<ApplicationUserManager>
{
DataProtectionProvider = new Microsoft.Owin.Security.DataProtection.DpapiDataProtectionProvider("ApplicationName")
}));
container.RegisterType<ApplicationSignInManager>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
Now detailed for MVC5 Owin integration on Autofac Docs:
"
Do all the stuff for standard MVC integration - register controllers, set the dependency resolver, etc.
Set up your app with the base Autofac OWIN integration.
Add a reference to the Autofac.Mvc5.Owin NuGet package.
In your application startup class, register the Autofac MVC middleware after registering the base Autofac middleware.
public class Startup
{
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
// STANDARD MVC SETUP:
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
// Run other optional steps, like registering model binders,
// web abstractions, etc., then set the dependency resolver
// to be Autofac.
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// OWIN MVC SETUP:
// Register the Autofac middleware FIRST, then the Autofac MVC middleware.
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
}
}
"
I also have RoleManager wrapper so added:
builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IdentityRole, string>>();
as per SO answer
I managed the workaround by using autofac service locator:
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
Yes, it is not good enough, but in the mean time, we could use object same scope as declared in autofac registration process.

Resources