【发布时间】:2022-01-02 23:37:50
【问题描述】:
我有一个应用程序在后端的 .NET Core 3.1 和前端的 Angular/Angular Materials 12 上运行,并且 OKTA 身份验证与 Angular/.NET Core 集成。
自从我将 Angular 代码从 Angular 9 更新到 12 并实现 Okta 后,我的 API 调用突然无法到达 .NET Core API 控制器中的实际 API 方法。
我的解决方案由一个 Web 应用程序和 API 项目构成。所有 API 控制器都存在于 API 项目中。为了弄清楚为什么 Angular 中的函数没有到达 API 端点,我在 TS 级别和服务级别包含了 console.log 语句。
当直接从浏览器点击它以及使用像 PostMan 这样的 API 检查器时,我已经验证了 API 方法和路径的工作原理。我冒险猜测它可能与 CORS 有关,但不完全确定。
UserManagementComponent.ts函数:
TestAPI() {
console.log("Inside Test API function. Next Step is to call the service for getting users tasks");
this.userManagementService.GetUserTasks();
}//End Test API
用户管理服务:
GetUserTasks(): Observable<Tasks[]> {
console.log("Made it to the GetUserTasks function inside service. ");
let methodName = "getUserTasks";
let attempts: any;
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
return this.http.get<Tasks[]>(this.url + '/' + methodName, httpOptions).pipe(
tap((UserTasksResponse: Tasks[]) => alert('resulting response data is: ' + JSON.stringify(UserTasksResponse))),
catchError((httpError: HttpErrorResponse) => {
console.log("Error Status code is: " + httpError.status + " and http error is: " + httpError.statusText);
console.log(this.handleError(httpError, methodName));
return this.handleError(httpError, methodName);
}),
//Eventually add in an attempts counter.
retryWhen(errors => errors.pipe(delay(750), take(4)))
);
}
API方法
[HttpGet]
[Route("/api/UserManagement/getUserTasks")]
public IActionResult GetUserManagementTasks()
{
// 1. Get the user's Id
var currentUser = new Guid("831AA34E-C96C-4C0D-DC89-08D7CDE02943");
// 2.Get the tasks assigned to the user. If the user id is an account owner id, get all tasks.
Data.Repositories.IUserRepository repo = new Data.Repositories.IUserRepository();
List<Tasks> userManagementTasks = repo.GetUserManagementTasks(currentUser);
// 3. Return all tasks to the UI.
return Ok(userManagementTasks);
}
网络项目Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
//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();
//}
} //End if env.IsDevelopment
}
API 项目Startup.cs:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseDeveloperExceptionPage();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
else { }
}
【问题讨论】:
-
你有没有试过测试一下这个api是否可以被postman之类的工具访问?如果api可以通过工具直接访问,恐怕您的问题来自前端,而不是您的api后端。
-
@TinyWang 是的。我做的第一件事是通过 POSTMAN 验证我的 API。我还验证了我可以从浏览器访问我的 API。在我的角度代码中,我有 console.log 检查。所以我知道 UI 元素正在点击 .TS 文件中的函数。我知道该功能正在到达上面显示的服务代码。当它到达 `return this.http.get
(this.url + '/' + methodName, httpOptions)` 行时,它不会离开角度到达 API。我已经 console.log 路径 (this.url + '/' + methodName, httpOptions)并验证了它的正确性。 -
有错误信息吗?我不熟悉 Angular,但这个问题看起来很奇怪。
-
浏览器控制台是否有任何错误/问题?
-
@Anuraj- 控制台中没有错误。解决方案在.Net端通过VS编译器/构建和角度命令ng b --watch编译,构建角度项目成功运行。
标签: angular asp.net-core .net-core app-startup