0

I am developing simple project using .NET Core Web API & Angular 14. But when I am trying to get the data from web api I am getting this error.

message: "Http failure response for https://localhost:7032/api/Student: 0 Unknown Error"

enter image description here

This is my angular student service codes

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

const baseURL = 'https://localhost:7032/api/Student';

@Injectable({
  providedIn: 'root'
})
export class StudentService {

  constructor(private httpClient: HttpClient) { }

  // get all students
  readAll(): Observable<any> {
    return this.httpClient.get(baseURL);
  }

  // get student by id
  read(id): Observable<any> {
    return this.httpClient.get('${baseURL}/${id}');
  }

  // create new student
  create(data): Observable<any> {
    return this.httpClient.post(baseURL, data);
  }

  // update student
  update(id, data): Observable<any> {
    return this.httpClient.put('${baseURL}/${id}', data);
  }

  // delete student
  delete(id): Observable<any> {
    return this.httpClient.delete('${baseURL}/${id}');
  }

  // delete all students
  deleteAll(): Observable<any> {
    return this.httpClient.delete(baseURL);
  }

  // search student by name
  searchByName(name): Observable<any> {
    return this.httpClient.get('${baseURL}?name=${name}');
  }
}

This is student list component codes

import { Component, OnInit } from '@angular/core';
import { StudentService } from 'src/app/services/student.service';

@Component({
  selector: 'app-student-list',
  templateUrl: './student-list.component.html',
  styleUrls: ['./student-list.component.css']
})
export class StudentListComponent implements OnInit {

  students: any;
  currentStudent = null;
  currentIndex = -1;
  firstName = '';

  constructor(private studentService: StudentService) { }

  ngOnInit(): void {
    this.readStudents();
  }

  readStudents(): void {
    this.studentService.readAll().subscribe(
      {
        next: (students) => this.students = students,
        error: (error) => console.log(error),
        complete: () => console.log("Completed")
      })
  }

  refresh(): void {
    this.readStudents();
    this.currentStudent = null;
    this.currentIndex = -1;
  }

  setCurrentStudent(student, index): void {
    this.currentStudent = student;
    this.currentIndex = index;
  }

  deleteAllStudents(): void {
    this.studentService.deleteAll()
      .subscribe(
        response => {
          console.log(response);
          this.readStudents();
        },
        error => {
          console.log(error);
        });
  }

  searchByName(): void {
    this.studentService.searchByName(this.firstName)
      .subscribe(
        students => {
          this.students = students;
          console.log(students);
        },
        error => {
          console.log(error);
        });
  }
}

In .Net Core Web API I have enable cros.

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddDbContext<StudentDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("StudentDbContext")
    ?? throw new InvalidOperationException("Connection string 'StudentDbContext' not found.")));

// Add services to the container.

builder.Services.AddControllers( options =>
{
    options.RespectBrowserAcceptHeader = false;
});

builder.Services.AddCors();

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

builder.Services.AddScoped<IStudentRepository, StudentService>();
builder.Services.AddScoped<ICourseRepository, CourseService>();

// Log Details 
var path = Directory.GetCurrentDirectory();

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File($"Logs/{Assembly.GetExecutingAssembly().GetName().Name}.log")
    .WriteTo.Console()
    .CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

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

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
else if (app.Environment.IsProduction())
{
    app.UseHttpsRedirection();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

Could someone can help to identify the issue ?

  • Almost certainly a CORS error. Little tip, if you have a network error in your js console, have a look at the network tab. – MikeOne Jul 17 '22 at 22:21
  • @MikeOne you get http error code 401 if its a CORS issue. I think the base URL is not correct here, but cant be proven until we try it on our end. – Amogh Sarpotdar Jul 18 '22 at 03:19
  • @MikeOne, Sarpotdar Do you guys have any idea how to resolve this issue. in my .NET Core API I have added UseCros() method. apart from that do I need to add anything ? – Sandanuwan Dharmarathna Jul 18 '22 at 05:19
  • @AmoghSarpotdar do you have any idea how to check this error. – Sandanuwan Dharmarathna Jul 18 '22 at 05:28
  • 1
    A few days back I got the same problem related to cors, this is because I entered the wrong port for my base URL, I checked launchSetting.json under the Properties folder and then I realized that I mistakenly use IIS Express's port number for my Base URL. This might be the case for you? – Synth Sloth Jul 18 '22 at 06:36
  • Ha! This is probably duplicate of https://stackoverflow.com/questions/47180634/i-get-http-failure-response-for-unknown-url-0-unknown-error-instead-of-actu . @SandanuwanDharmarathna please go through the post above. – Amogh Sarpotdar Jul 18 '22 at 06:46

0 Answers0