這是一個 Blazer 服務器應用程式,我無法使用 ApiService 從控制器獲取值,我從 Index.razor 頁面的 @code 部分呼叫 api 服務方法。
Index.razor
@code {
private List<SystemUser> systemUsers;
private List<RegisterUserModel> registerUserModels = new List<RegisterUserModel>();
private RegisterUserModel registerUserModel = null;
protected override async Task OnInitializedAsync()
{
try
{
systemUsers = await SystemUsersService.GetSystemUsers();
if (systemUsers != null && systemUsers.Count > 0)
{
foreach (SystemUser systemUser in systemUsers)
{
registerUserModel = new RegisterUserModel()
{
FirstName = systemUser.FirstName
,
LastName = systemUser.LastName
,
Email = systemUser.Email
,
UserName = systemUser.UserName
,
Password = systemUser.Password
};
registerUserModels.Add(registerUserModel);
}
}
}
catch (Exception exception)
{
Console.WriteLine("Error " exception);
}
}
}
服務類
public class SystemUsersService
{
private readonly IHttpClientFactory _clientFactory;
public SystemUsersService(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<List<SystemUser>> GetSystemUsers()
{
var result = new List<SystemUser>();
try
{
var url = string.Format("https://localhost:44391/systemusers/get");
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/json");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
result = JsonSerializer.Deserialize<List<SystemUser>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
}
else
{
result = Array.Empty<SystemUser>().ToList();
}
} catch (Exception exception)
{
throw exception;
}
return result;
}
}
}
控制器
namespace ServerWebAppForCW.Controllers
{
[ApiController]
[Route("[controller]")]
public class SystemUserController : ControllerBase
{
[HttpGet("/systemusers/get")]
public async Task<IEnumerable<SystemUser>> GetAll()
{
var model = new List<SystemUser>();
RegisterUserModel registerUserModel = new RegisterUserModel();
model = await registerUserModel.GetSystemUsers();
return model;
}
[HttpGet("/systemusers/create")]
public async Task<Boolean> CreateSystemUser(RegisterUserModel registerUserModel)
{
return await registerUserModel.CreateSystemUser();
}
}
}
從 Service 類的下面一行,我在這里得到的回應是內容中的一個奇怪的 html doc 型別的東西,盡管狀態代碼是 200,但在除錯 SendAsync 時沒有呼叫控制器方法“GetAll()”。所以我不知道這個呼叫從哪里獲取資料。
var response = await client.SendAsync(request);
這是影像
api 呼叫回應
繼續,在他下面的行中拋出了一個錯誤
result = JsonSerializer.Deserialize<List<SystemUser>>(stringResponse,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
由于 JsonSerilizer 試圖反序列化 html 回應,哪種方式有意義。
例外錯誤圖片
例外錯誤影像
文字錯誤:
{"'<' is an invalid start of a value. Path: $ | LineNumber: 1 | BytePositionInLine: 0."}
所以我的問題是為什么我得到這個奇怪的 html 回應而不是 HttpClientFactory 呼叫不呼叫我的控制器的 api?
希望有人能解釋一下這種情況。
僅供參考我的啟動注入
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddScoped<SystemUserService>();
services.AddSingleton<SystemUsersService>();
services.AddDbContext<AppDBContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));
services.AddHttpClient();
}
uj5u.com熱心網友回復:
services.AddRazorPages()
不提供對 API 的支持。
要提供 API 路由,請使用以下任一項:
services.AddMvc();
services.AddControllers();
services.AddControllersWithViews();
AddControllers 是支持 API 的最小實作。
https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio#mvc-service-registration
uj5u.com熱心網友回復:
我在 ConfigureServices 方法的末尾將此相關代碼添加到我的 Startup.cs
services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
配置服務:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddScoped<SystemUserService>();
//This one AddMvc
services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddDbContext<AppDBContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));
services.AddScoped<HttpClient>();
}
還要將此行添加到“app.UseRouting();”之后的 Startup.cs 類的 Configure 方法中。
app.UseMvcWithDefaultRoute();
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/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.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/371722.html
