Post action not working in controller but working in another controller

I have a project that allows users to create a new project. The UI has some textboxes and a submit button. It sends data through a POST request to an api call, which then creates a new project entity in the database. I deleted my migrations and then added a new migration since I wanted to fix some code, but now the post action no longer works. I see the following error message in the console –

System.InvalidOperationException: Unable to resolve service for type
‘AutoMapper.IMapper’ while attempting to activate
‘IssueTracker.Controllers.ProjectController’.

Create new project

// POST api/values
[HttpPost]
public void Post([FromBody] Projects project)
{
    _repository.CreateProject(project);
    _repository.SaveChanges();
}

Projects Model
public class Projects
{
    public Projects(string name, string description)
    {
        this.name = name;
        this.description = description;
    }

    public Projects()
    {
        //
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string id { get; set; }
    
    [Required]
    public string name { get; set; }
    
    [Required]
    public string description { get; set; } 
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As your error message indicates you have AutoMapper installed but it is not being registered/resolved by the dependency injector.

Install the package AutoMapper.Extensions.Microsoft.DependencyInjection and add the following line in the ConfigureServices method in Startup.cs file –

services.AddAutoMapper(typeof(Startup));

This will do if the Startup class and your mapping profile class/classes are in the same assembly/project. If they are not, then use the following –
services.AddAutoMapper(typeof(MyMappingProfileClass));

where MyMappingProfileClass is the mapping profile class where you have defined/configured your maps.

Method 2

I suggest to use Newton.Json nuget package, then pass a ViewModel back to controller without [FromBody]. Could you give it a try?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x