[英]Consuming asp.net core web api in asp.net core mvc web app
我正在嘗試在我的 asp.net 核心 mvc web 應用程序中使用我的 asp.net web api 應用程序,它們都在同一個解決方案上。 我為多項目啟動配置了解決方案,它們都啟動了。
接下來,我嘗試在 Web 部分中使用 API,但出現以下錯誤。
InvalidOperationException:找不到適合類型“ProjectName.Web.Services.Interfaces.IAdminService”的構造函數。 確保類型是具體的,並且公共構造函數的所有參數都注冊為服務或作為 arguments 傳遞。還要確保沒有提供無關的 arguments。 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.FindApplicableConstructor(類型 instanceType,類型 [] argumentTypes,輸出 ConstructorInfo matchingConstructor,輸出 Nullable [] matchingParameterMap)
項目的結構是這樣的
解決方案名稱:
姓名.API
姓名.Web
每個都有自己的結構
這是我的幫手 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;
}
}
IAdmin 界面
Task<IEnumerable<Admins>> GetAllAdmins();
AdminService(實現)
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>>();
}
管理員 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);
}
程序.cs
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient<IAdminService, IAdminService>(c =>
c.BaseAddress = new Uri("https://localhost:<port-Num>/"));
var app = builder.Build();
我做錯了什么??? 我正在使用.NET 6
並且兩個項目都在同一個解決方案中
注意我的端點工作正常,我使用 Postman 測試它們。
它失敗了,因為 DI 無法使用參數化構造函數實例化您的 AdminService。 這可能是Combining DI with constructor parameters 的副本? .
本質上,您應該盡可能避免參數化構造函數注入。 要么通過配置控制它,要么通過主機配置等公共基礎設施加載配置。
根據您的代碼,我發現您在導致問題的 AddHttpClient 方法中放置了兩個接口。
我建議你可以這樣修改它,然后它會很好地工作。
builder.Services.AddHttpClient<IAdminService, AdminService>(c =>
c.BaseAddress = new Uri("https://localhost:3333/"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.