1

I have an application running on .NET Core 3.1 on the back-end and Angular/Angular Materials 12 on the front-end and an OKTA Authentication integration with Angular/.NET Core.

Since I updated the angular code from Angular 9 to 12 and implemented Okta, my API calls are suddenly not reaching the actual API method in the .NET Core API controller.

My solution is structured with a web application and API project. All API controllers live in the API project. In an attempt to figure out why the function in angular is not hitting the API endpoint, I've included console.log statements at the TS level and the service level.

I've verified the API method and path work when hitting it directly from a browser and when using an API inspector like PostMan. I'm venturing a guess that its possibly CORS related, but not completely sure.

UserManagementComponent.ts function:

TestAPI() {
    console.log("Inside Test API function. Next Step is to call the service for getting users tasks");
    this.userManagementService.GetUserTasks();

  }//End Test API

User Management Service:

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 Method

[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);
}

Web project 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 project 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 { }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alex
  • 443
  • 3
  • 18
  • Did you try to test if the api can be accessed by tools like postman? I'm afraid your issue came from the front-end, but not your api backend if the api can be accessed directly by tools. – Tiny Wang Jan 03 '22 at 01:42
  • @TinyWang Yes. the first thing I did was verify my API through POSTMAN. I've also verified I can hit my API from a browser. Within my angular code, I have console.log checks. So I know the UI element is hitting the function in the .TS file. I know that function is reaching the service code shown above. Its when it gets to the line ` return this.http.get(this.url + '/' + methodName, httpOptions)` that its not leaving angular to reach the API. I've console.log the path `(this.url + '/' + methodName, httpOptions)` and verified its correct. – Alex Jan 03 '22 at 01:50
  • Is there any error message? I'm not familiar with Angular but the issue looks weird. – Tiny Wang Jan 03 '22 at 02:20
  • Is there any errors/issues in the browser console? – Anuraj Jan 03 '22 at 02:37
  • @Anuraj- No errors in the console. Solution compiled both on the .Net side through VS compiler/build and the angular command ng b --watch to build the angular project successfully runs. – Alex Jan 03 '22 at 03:50
  • Can you check your network tab and see the request/response values? – klekmek Jan 03 '22 at 09:30

1 Answers1

1

In the startup.cs file add the code as given below.it will be work.

app.UseCors(options => options.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader());
Sathiya
  • 250
  • 2
  • 2