Hi all I do have an issue with my auto mapping objects in my case I need properties to be skipped over and map the db context properties with my custom object
here is how I'm trying to convert the object but i am getting an error
System.NullReferenceException: 'Object reference not set to an instance of an object
var library = await Task.FromResult(mapper.Map<test.WebApi.Dto.Library>(item));
here is my custom mapper class
public class CustomMapper: Profile
{
public CustomMapper()
{
CreateMap<test.WebApi.Models.Library, test.WebApi.Dto.Library>().ForMember(dest => dest.Id, opt => opt.Ignore());
}
}
here are my dto class and the dbcontext classes
using System;
using System.Collections.Generic;
#nullable disable
namespace test.WebApi.Models
{
public partial class Library
{
public Library()
{
GeneratedFiles = new HashSet<GeneratedFile>();
Templates = new HashSet<Template>();
}
public int Id { get; set; }
public long? TenantId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<GeneratedFile> GeneratedFiles { get; set; }
public virtual ICollection<Template> Templates { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace test.WebApi.Dto
{
public class Library
{
public int Id { get; set; }
public long TenantId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
packages and info
AutoMapper 10.1.1
AutoMapper.Extensions.Microsoft.DependencyInjection 8.1.1
.net core 5.0
Here is a whole working demo:
public class HomeController : Controller
{
private readonly IMapper mapper;
public HomeController(IMapper mapper)
{
this.mapper = mapper;
}
public void Index()
{
var item = new test.WebApi.Models.Library()
{
Description = "aa"
};
var library = await Task.FromResult(mapper.Map<test.WebApi.Dto.Library>(item));
}
}
Startup.cs:
services.AddAutoMapper(typeof(CustomMapper));
I'm trying to implement a GraphQL API that in .NET using Hot Chocolate 12.3.2. I'm able to get the project to build and run. When attempting to test my query CakePop the browser loads fine but there is no schema present.
startup.cs
namespace Application
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
[Obsolete]
public void ConfigureServices(IServiceCollection services)
{
services.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<BillType>().AddGraphQL()
.BindRuntimeType<DateOnly, DateType>()
.AddTypeConverter<DateOnly, DateTime>(from => DateTime.Parse(from.ToString()))
.AddTypeConverter<DateTime, DateOnly>(from => DateOnly.FromDateTime(from));
services.AddGraphQL(sp => SchemaBuilder.New().AddServices(sp).Create())
.AddPooledDbContextFactory<WeVoteContext>(b =>b.UseInMemoryDatabase("Test"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app
.UseRouting()
.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL().WithOptions(new GraphQLServerOptions
{
EnableSchemaRequests = true,
Tool = {
Enable = env.IsDevelopment()
}
});
});
}
}
}
query.cs
namespace Application
{
public class Query
{
static ApplicationContext db = new ApplicationContext();
public IEnumerable<LegiscanModelBill> GetBills(int N)
{
return db.LegiscanModelBills.Take(N).AsEnumerable();
}
}
}
Models/LegiscanModelBill.cs
namespace Application.Models
{
public partial class LegiscanModelBill
{
[GraphQLIgnore]
public int Id { get; set; }
public string? BillNumber { get; set; }
public string? ChangeHash { get; set; }
public string? Url { get; set; }
[GraphQLIgnore]
public DateOnly? StatusDate { get; set; }
public int? StatusId { get; set; }
[GraphQLIgnore]
public DateOnly? LastActionDate { get; set; }
public string? LastAction { get; set; }
public string? Title { get; set; }
public string? Description { get; set; }
[GraphQLIgnore]
public DateTime CreatedAt { get; set; }
[GraphQLIgnore]
public DateTime UpdatedAt { get; set; }
public int? SessionId { get; set; }
public int? UpvotesCount { get; set; }
public int? BodyId { get; set; }
public DateTime? LegiscanDataUpdatedAt { get; set; }
public int? BillId { get; set; }
public int? CommentsCount { get; set; }
public double? Hotness { get; set; }
public string? Texts { get; set; }
public int? CommitteeId { get; set; }
public int? BillTypeId { get; set; }
public string? StateLink { get; set; }
}
public class BillType : ObjectType<LegiscanModelBill>
{
}
}
Nothing is in the logs
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
Updated Service
public void ConfigureServices(IServiceCollection services)
{
services
.AddPooledDbContextFactory<WeVoteContext>(b => b.UseInMemoryDatabase("Test"))
.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<BillType>();
// .BindRuntimeType<DateOnly, DateType>()
// .AddTypeConverter<DateOnly, DateTime>(from => from.ToDateTime(default))
// .AddTypeConverter<DateTime, DateOnly>(from => DateOnly.FromDateTime(from.Date));
}
The setup code seems to have an issue ... you are mixing legacy API and the new configuration API.
services
.AddPooledDbContextFactory<WeVoteContext>(b =>b.UseInMemoryDatabase("Test"))
.AddGraphQLServer()
.AddQueryType<Query>()
.AddType<BillType>()
.BindRuntimeType<DateOnly, DateType>()
.AddTypeConverter<DateOnly, DateTime>(from => from.ToDateTime(default))
.AddTypeConverter<DateTime, DateOnly>(from => DateOnly.FromDateTime(from.Date));
With 12.4.0-preview.8 we have shipped support for TimeOnly and DateOnly.
When you move to 12.4 remove the explicit binding and the converters.
Also, you can remove the GraphQLIgnore attributes with this configuration again.
I'm using the Nuget package AutoMapper.Extensions.Microsoft.DependencyInjection version 7.0.0, in an ASP.Net Core 3 Web API project.
When I use the Map() method...
IEnumerable<SchoolForListDto> schoolsToReturn = _mapper<IEnumerable<School>, IEnumerable<SchoolForListDto>>.Map(schools);
... I receive the following error message:
Type arguments in method IMapper.Map<TDestination>(object) cannot be inferred from the usage. Try specifying the type arguments explicitly.
The complete code:
Models/Holder.cs
using System;
using System.Collections.Generic;
namespace SchoolApi.Models
{
public class Holder
{
public string Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual ICollection<School> Schools { get; set; }
}
}
Models/School.cs
using System;
using System.Collections.Generic;
namespace SchoolApi.Models
{
public class School
{
public string Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string WebSite { get; set; }
public string Address { get; set; }
public string HolderId { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual Holder Holder { get; set; }
}
}
Data/DataContext.cs
using Microsoft.EntityFrameworkCore;
using SchoolApi.Models;
namespace SchoolApi.Data
{
public class DataContext : DbContext
{
public DbSet<Holder> Holders { get; set; }
public DbSet<School> Schools { get; set; }
public DataContext(DbContextOptions<DataContext> options)
: base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
}
Data/IGenericRepository
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SchoolApi.Data
{
public interface IGenericRepository<TEntity> where TEntity : class
{
void Add(TEntity entity);
void Delete(TEntity entity);
Task<TEntity> Get(object id);
Task<IEnumerable<TEntity>> GetAll();
Task<bool> SaveAll();
void Update(TEntity entity);
}
}
Data/GenericRepository
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace SchoolApi.Data
{
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
private readonly DataContext _dataContext;
private readonly string _entityName = typeof(TEntity).FullName;
public GenericRepository(DataContext dataContext)
{
_dataContext = dataContext;
}
public void Add(TEntity entity)
{
_dataContext.Set<TEntity>().Add(entity);
}
public void Delete(TEntity entity)
{
_dataContext.Set<TEntity>().Remove(entity);
}
public async Task<TEntity> Get(object id)
{
TEntity entity = await _dataContext.Set<TEntity>().FindAsync(id);
return entity;
}
public async Task<IEnumerable<TEntity>> GetAll()
{
IEnumerable<TEntity> entities = await _dataContext.Set<TEntity>().ToListAsync();
return entities;
}
public async Task<bool> SaveAll()
{
int result = await _dataContext.SaveChangesAsync();
return result > 0;
}
public void Update(TEntity entity)
{
_dataContext.Set<TEntity>().Update(entity);
}
}
}
Dtos/SchoolForListDto.cs
namespace SchoolApi.Dtos
{
public class SchoolForListDto
{
public string Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string HolderName { get; set; }
}
}
Helpers/AutoMapperProfiles
using AutoMapper;
using SchoolApi.Dtos;
using SchoolApi.Models;
namespace SchoolApi.Helpers
{
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<School, SchoolForListDto>()
.ForMember(dest => dest.HolderName, opt => opt.MapFrom(src => src.Holder.Name));
}
}
}
Startup.cs
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SchoolApi.Data;
using SchoolApi.Models;
namespace SchoolApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
services.AddCors();
services.AddDbContext<DataContext>(options => options.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAutoMapper(typeof(Startup));
services.AddScoped<IGenericRepository<School>, GenericRepository<School>>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Controllers/SchoolController.cs
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SchoolApi.Data;
using SchoolApi.Dtos;
using SchoolApi.Models;
namespace SchoolApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SchoolController : ControllerBase
{
private readonly IGenericRepository<School> _repository;
private readonly IMapper _mapper;
private readonly ILogger<SchoolController> _logger;
public SchoolController(IGenericRepository<School> repository, IMapper mapper, ILogger<SchoolController> logger)
{
_repository = repository;
_mapper = mapper;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
IEnumerable<School> schools = await _repository.GetAll();
// The error occurs on the following line
IEnumerable<SchoolForListDto> schoolsToReturn = _mapper<IEnumerable<School>, IEnumerable<SchoolForListDto>>.Map(schools);
return Ok(schoolsToReturn);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get([FromRoute] string id)
{
School school = await _repository.Get(id);
SchoolForListDto schoolToReturn = _mapper.Map<SchoolForListDto>(school);
return Ok(schoolToReturn);
}
}
}
These are the packages that I am using:
- AutoMapper.Extensions.Microsoft.DependencyInjection (version 7.0.0)
- Microsoft.AspNetCore.Mvc.NewtonsoftJson (version 3.1.4)
- Microsoft.EntityFrameworkCore (version 3.1.4)
- Microsoft.EntityFrameworkCore.Design (version 3.1.4)
- Microsoft.EntityFrameworkCore.Proxies (version 3.1.4)
- Microsoft.EntityFrameworkCore.Relational (version 3.1.4)
- Microsoft.EntityFrameworkCore.SqlServer (version 3.1.4)
Target framework: DotNet Core 3.1
IDE: Visual Studio Code
SO: Windows 10
GitHub repository: https://github.com/jmcandia/SchoolApi
Thanks #TimothyMacharia for your suggestion. It effectively helped me to correct the problem.
I changed this code...
IEnumerable<SchoolForListDto> schoolsToReturn = _mapper<IEnumerable<School>, IEnumerable<SchoolForListDto>>.Map(schools);
... for this one and it worked.
IEnumerable<SchoolForListDto> schoolsToReturn = _mapper.Map<IEnumerable<SchoolForListDto>>(schools);
I've created a brand new Visual Studio 2019 web app using ASP.Net Core 3.1 with an MVC pattern.
My controller has an HttpPost method that should have an incoming Json object (I use [FromBody] for the incoming parameter).
No matter what I try, the incoming parameter is always Null. I've tried changing the parameter to a string, and modifying the Model to be a simple 3 field class, but it still comes in as a null.
I used Chrome's Developer Tools to make sure that my page is sending the Json object correctly from a JavaScript Post callback (and also used Postman to do the same) with the same result: my parameter is still Null.
What do I need to do to get the parameter to come in as an actual value?
My controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using canvasApiLib.API;
using CanvasGrades.Models.AuxiliaryModels;
namespace CanvasGrades.Controllers
{
public class FinalGradeController : Controller
{
public async Task<IActionResult> Index()
{
// Course Name
dynamic courseDetails = await clsCoursesApi.getCourseDetails(accessToken, apiUrl, canvasCourseId);
ViewData["CourseName"] = courseDetails.name;
// Course Term
dynamic courseTerm = await clsEnrollmentTermsApi.getEnrollmentTerm(accessToken, apiUrl, canvasAccountID, termNum);
ViewData["CourseTerm"] = courseTerm.name;
return View();
}
[HttpPost]
public async Task<IActionResult> LoadTable([FromBody]DTParameters dtParameters)
{
//DTParameters dtParameters = new DTParameters();
if (dtParameters == null)
{
dtParameters = new DTParameters();
}
}
}
}
My DTParameters model:
public class DTParameters
{
public int Draw { get; set; }
public DTColumn[] Columns { get; set; }
public DTOrder[] Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public DTSearch Search { get; set; }
public IEnumerable<string> AdditionalValues { get; set; }
}
Most examples that I saw stated to tweak the app.UseMVC instantiation in the Configure call of the Startup.cs file, but mine doesn't have one:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
(ADDED)
{"draw":1,"columns":[{"data":"studentName","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":"studentEMail","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":null,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":"finalGrade","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":"lastAttendDate","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":null,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":null,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":"bannerID","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":"crn","name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}],"order":[{"column":0,"dir":"asc"}],"start":0,"length":10,"search":{"value":"","regex":false}}
I retried my simple parameter again, noticing that original ID field that I sent was an integer, but when I made it a string (like the Model stated) it came in with no issue.
public class SimpleParam
{
public string Id { get; set; }
public string Name { get; set; }
public string Foo { get; set; }
}
{"id": "1", "name": "fred", "foo": "bob"}
So, that means I'm going to have to figure out what's wrong with my DTParameters model.
The error is "dir": "asc". You need to either change this to an int ("dir": 0), or decorate the class property or the enumeration with
[JsonConverter(typeof(JsonStringEnumConverter))]
or put this in startup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())
);
//...
}
Your input beautified:
{
"draw": 1,
"columns": [
{
"data": "studentName",
"name": "",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
}
],
"order": [
{
"column": 0,
"dir": "asc"
}
],
"start": 0,
"length": 10,
"search": {
"value": "",
"regex": false
}
}
Your Datatables classes with correct decoration (See above DTOrderDir):
public class DTParameters
{
public int Draw { get; set; }
public DTColumn[] Columns { get; set; }
public DTOrder[] Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public DTSearch Search { get; set; }
public IEnumerable<string> AdditionalValues { get; set; }
}
public class DTColumn
{
public string Data { get; set; }
public string Name { get; set; }
public bool Searchable { get; set; }
public bool Orderable { get; set; }
public DTSearch Search { get; set; }
}
public class DTOrder
{
public int Column { get; set; }
public DTOrderDir Dir { get; set; }
}
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum DTOrderDir
{
ASC,
DESC
}
public class DTSearch
{
public string Value { get; set; }
public bool Regex { get; set; }
}
Read here for more info: JavaScriptSerializer - JSON serialization of enum as string
I have the following classes:
public class Quiz
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string UserToken { get; set; }
public List<JoinQuizAndArea> AreasOfQuizzes { get; set; }
public List<QuizQuestion> Questions { get; set; }
}
public class QuizQuestion
{
public int ListRanking { get; set; }
public string Question { get; set; }
public string Answer1 { get; set; }
public string Answer2 { get; set; }
public string Answer3 { get; set; }
public int CorrectAnswer { get; set; }
public int QuizId { get; set; }
public Quiz Quiz { get; set; }
}
public class AreaOfQuiz
{
public int Id { get; set; }
public string Area { get; set; }
public List<JoinQuizAndArea> AreasOfQuizzes { get; set; }
}
public class JoinQuizAndArea
{
public int QuizId { get; set; }
public Quiz Quiz { get; set; }
public int AreaId { get; set; }
public AreaOfQuiz Area { get; set; }
}
and my DbContext:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public DbSet<IdentityUser> Users { get; set; }
public DbSet<Quiz> Quizzes { get; set; }
public DbSet<AreaOfQuiz> Areas { get; set; }
public DbSet<QuizQuestion> Questions { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<IdentityUser>();
modelBuilder.Entity<Quiz>();
modelBuilder.Entity<AreaOfQuiz>();
modelBuilder.Entity<QuizQuestion>()
.HasKey(quizQuestion => new { quizQuestion.QuizId, quizQuestion.ListRanking});
modelBuilder.Entity<JoinQuizAndArea>()
.HasKey(joinEntity => new { joinEntity.QuizId, joinEntity.AreaId });
modelBuilder.Entity<JoinQuizAndArea>()
.HasOne(join => join.Area)
.WithMany(c =>c.AreasOfQuizzes)
.HasForeignKey(join => join.QuizId);
modelBuilder.Entity<JoinQuizAndArea>()
.HasOne(bc => bc.Quiz)
.WithMany(c => c.AreasOfQuizzes)
.HasForeignKey(bc => bc.AreaId);
base.OnModelCreating(modelBuilder);
}
}
when I try to create the initial migration I got the following error:
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Custom configuration for members is only supported for top-level individual members on a type.
Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Do someone have an idea how to resolve this problem?? Thanks :)
Update
My start Up class:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
var mappingConfig = new MapperConfiguration(mapConfig =>
{
mapConfig.AddProfile(new QuizProfile());
mapConfig.AddProfile(new AreaOfQuizProfile());
mapConfig.AddProfile(new QuizQuestionProfile());
mapConfig.AddProfile(new QuizIdAreaIdToJoinQuizAndAreaProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["ConnectionString:QuizWorldDb"]));
services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(config =>{
config.RequireHttpsMetadata=false;
config.SaveToken = true;
config.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Secret"])),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
For me, unload docker-compose worked.
Clean and Build.
Run Migration.