Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi!

I have an angular 8 dotnet api project in which I have a problem with the post method in register.service.ts as it should return 200 ok,but instead it returns 415 unsupported media type.I am struggling with this error for some time and I understood that it appears when the CORS middleware is not enabled properly.I did that in startup.cs as follows:
 public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddDbContext<DataContext>(options => options.UseMySql(Configuration.GetConnectionString("DataContext")));
            services.AddControllersWithViews();
            services.AddApiVersioning(options =>
 {
  options.UseApiBehavior = true;
  options.AssumeDefaultVersionWhenUnspecified = true;
 });
 
 
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist/";
            });
            services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy",
        builder => builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader().WithOrigins("http://localhost:5001"));
});
 services.AddScoped(typeof(IUserService<>), typeof(UserService<>));
        }

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.UseOptions();

           app.UseHttpsRedirection();
           app.UseStaticFiles();
           if (!env.IsDevelopment())
           {
               app.UseSpaStaticFiles();
           }

           app.UseRouting();
           app.UseCors("CorsPolicy");
           app.UseEndpoints(endpoints =>
           {
               endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller}/{action=Index}/{id?}");
           });

           app.UseSpa(spa =>
           {
               // To learn more about options for serving an Angular SPA from ASP.NET Core,
               // see https://go.microsoft.com/fwlink/?linkid=864501

               spa.Options.SourcePath = "ClientApp";

               if (env.IsDevelopment())
               {
                   spa.UseAngularCliServer(npmScript: "start");
               }
           });
       }

I also enable CORS in the controller as follows:
 [EnableCors("CorsPolicy")]
[Produces("application/json")]
    [Route("[controller]")]
    [ApiController]
    public class RegisterController : ControllerBase



this is the register.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment'; import { Register } from '../Models/register';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';




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

baseurl = 'http://localhost:5001/register/';
  constructor(private http: HttpClient) { }
Create(user): Observable<Register> {
  const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=UTF-8'}) };
  return this.http.post<Register>(this.baseurl, JSON.stringify(user), httpOptions).pipe(retry(1), catchError(this.errorHandler));
  }


As you can see,I am declaring the baseurl variable in order to pass it to the method along with the header which has the format application/json.The problem is that,for some reason the error still persists,but for get method it displays the data in "register" as json format without any problem.
In the console I have the following errors:
zone-evergreen.js:2828 POST http://localhost:5001/register/ net::ERR_EMPTY_RESPONSE

core.js:5873 ERROR Error Code: 0
Message: Http failure response for http://localhost:5001/register/: 0 Unknown Error


Again,I read that the "0 Unknown Error" is because the CORS middleware is not set properly but I have checked it a million times and it seems fine.I have no ideas why is not working because theoretically it should.In my register.component.ts I have the following:
import { Component, OnInit, Injectable, ChangeDetectorRef, ChangeDetectionStrategy, Input } from '@angular/core';
import { RegisterService } from '../services/register.service';
import { FormBuilder, FormGroup} from '@angular/forms';
import { Register } from '../Models/register';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
@Injectable({ providedIn: 'root' })
export class RegisterComponent implements OnInit {
 userIdForDelete: number = null;
@Input() user: Register = new Register();
 form: FormGroup;
 actionType: string;
 formName: string;
formPassword:string;
 userId: number;
 formEmail: string;
 message: any;

constructor(private regService:RegisterService,private formBuilder: FormBuilder, private avRoute:ActivatedRoute, private router:Router ) { 
  const idParam = 'id';
  this.actionType = 'Add';
  this.formName = 'name';
  this.formEmail = 'email';
  this.formPassword = 'password';
  if (this.avRoute.snapshot.params[idParam]) {
    this.userId = this.avRoute.snapshot.params[idParam];
  }
  this.form = this.formBuilder.group({
    userId: 0,
    name: [''],
    email: [''],
    password: ['']
  });
}
ngOnInit() {

  }
PostRegister() {
if (!this.form.valid) {
  return;
}
if (this.actionType === 'Add') {
// tslint:disable-next-line:prefer-const
let register: Register = {
email: this.form.get(this.formEmail).value,
name: this.form.get(this.formName).value,
password: this.form.get(this.formPassword).value
};
this.regService.Create(register).subscribe((data) => {
this.message('Registered succesfully');
});
}
}
}


The PostRegister() i then assign it to the ngSubmit event in my register.component.html as follows:
<form [formGroup]="form" (ngSubmit)="PostRegister()" #formDir="ngForm" novalidate>

Please let me know if you have some thoughts as to why the error still persists considering that everything looks fine.Any help would be really appreciated and let me know if you need extra info regarding the code.Best regards!

What I have tried:

I have tried to set the name of the route in my UserController.cs for post method as follows:
[Route("PostRegister")]
[HttpPost]
       public async Task<ActionResult<Register>> PostRegister([FromBody] Register register)
       {
           if (!ModelState.IsValid)
       {
           return BadRequest(ModelState);
       }

       _repo.Add(register);
       var save = await _repo.SaveAsync(register);
            return CreatedAtAction(nameof(GetRegister), new { id = register.Id }, register);
       }

and I got 405 Method Not Allowed from posting to url:https://localhost:5001/register/.


I also changed the httpOptions const to this:
const httpOptions = { headers: new HttpHeaders({ 'Content-Type':'application/x-www-form-urlencoded','Access-Control-Allow-Origins':'*'})};
Posted
Updated 9-Mar-22 10:25am
v2

1 solution

Hi
I had almost the same problem but only with string, when i sent it in Postman it was working correct, but in VS Code not.
What I did?
I added httpOptions
httpOptions = {
    headers : ({'Content-Type': 'application/json'})
    }

And also make JSON.stringify()
get(task:string){
       return this.http.post(this.url,JSON.stringify(task), this.httpOptions)
   }

Hope that it'll help you
Best wishes
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900