Home > database >  Consuming asp.net core web api in asp.net core mvc web app
Consuming asp.net core web api in asp.net core mvc web app

Time:01-11

I'm trying to consume my asp.net web api in my asp.net core mvc web app which are on the same solution. I configured the solution for multi-project start and they start both.

next I tried to consume the API in the Web part but I'm getting the following error.

InvalidOperationException: A suitable constructor for type 'ProjectName.Web.Services.Interfaces.IAdminService' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out Nullable[] matchingParameterMap)

Here is the complete Stack trace enter image description here

The Projects are structure like this

SolutionName:
Name.API
Name.Web

each with its own respective structure

This is my Helper Class

public static class HttpClientExtensions
    {
        public static async Task<T> ReadContentAsync<T>(this HttpResponseMessage response)
        {
            //if (response.IsSuccessStatusCode == false) return StatusCodes =  300;
                //throw new ApplicationException($"Something went wrong calling the API: {response.ReasonPhrase}");
                
            var dataAsString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var result = JsonSerializer.Deserialize<T>(
                dataAsString, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

            return result;
        }
    }

The IAdmin Inter Face

Task<IEnumerable<Admins>> GetAllAdmins();

The AdminService(Implementation)

private readonly HttpClient _client;
        public const string BasePath = "api/Admins";

        public AdminService(HttpClient client)
        {
            _client = client; // ?? throw new ArgumentNullException(nameof(client));
        }

        public async Task<IEnumerable<Admins>> GetAllAdmins()
        {
            var response = await _client.GetAsync(BasePath);

            return await response.ReadContentAsync<List<Admins>>();
        }

Admins Controller

     private readonly IAdminService _adminService;

        public AdminController(IAdminService adminService)
        {
            _adminService = adminService;
        }


        public async Task<IActionResult> Index()
        {
            var adminsList = await _adminService.GetAllAdmins();

            if(adminsList == null)
            {
                return new JsonResult("There are now Admins");
            }

            return View(adminsList);
        }

Program.cs

builder.Services.AddControllersWithViews();

builder.Services.AddHttpClient<IAdminService, IAdminService>(c =>
c.BaseAddress = new Uri("https://localhost:<port-Num>/"));


var app = builder.Build();

What Could I be doing wrong??? I'm using .NET 6 adn both Projects are in the same solution

NB My end points are working fine, I test them using Postman.

CodePudding user response:

It is failing because DI cannot instantiate your AdminService with parameterized constructor. This is possibly a duplicate of Combining DI with constructor parameters? .

Essentially, you should avoid parameterized constructor injection where possible. Either control it through configuration or have the configuration loaded through common infrastructure such as host configuration.

CodePudding user response:

According to your codes, I found you put two interface inside the AddHttpClient method which caused the issue.

I suggest you could modify it like this and then it will work well.

builder.Services.AddHttpClient<IAdminService, AdminService>(c =>
c.BaseAddress = new Uri("https://localhost:3333/"));
  • Related