Home > front end >  Access to XMLHttpRequest at 'http://localhost:54111/RegisterController' from origin '
Access to XMLHttpRequest at 'http://localhost:54111/RegisterController' from origin '

Time:10-07

I know that there are some other questions on this topic, but no answer could help me. I am trying to send registration form's data from Angular Cli project to my MVC server side project. What I have done so far:

On Angular, the registration function:

import { Component, OnInit, Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material';
import { Route, Router } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { HttpClient } from '@angular/common/http';
import { analyzeAndValidateNgModules } from '@angular/compiler';

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

  ngOnInit() {}
  
 data: any;

   constructor(private snackBar:MatSnackBar, private router: Router, private http:HttpClient){}

   onSubmitRegistration(users: {rEmail: string, rPassword: string, rRepeatPassword: string}){
      console.log(users);

          this.http.post('http://localhost:54111/RegisterController', users, {withCredentials: true}).subscribe(data => {
            console.log(data);
  })
      
   }

   login() {
    //login code
   }
 }

On MVC server side, the RegistrationController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ServerSide.Controllers
{
    public class RegisterController : ApiController
    {
        string emailRegister;

        public class Data{
            public string email { get; set; }
            public string password { get; set; }
            public string repeatPass { get; set; }
            
        }


        [HttpPost, AllowCrossSite]
        public string PostValue(Data d)
        {
            emailRegister = d.email;
            System.Diagnostics.Debug.WriteLine("***************************************EmailRegister "   emailRegister   "***************************************");
            return "value";
        }
    }
}

Also on server side project, I have a class called AllowCrossSiteAttribute with the following content:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ServerSide.Controllers
{
    public class AllowCrossSiteAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
              filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200/login");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE,PUT");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Authorization");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
            base.OnActionExecuting(filterContext);
        }
    }
}

When I click the registration button, I get this error: enter image description here

Could you please tell me what am I missing?

CodePudding user response:

You need to set cors policy in your applicaton by adding folowing code in program.cs file.

string[] origins = builder.Configuration.GetSection("MyConfig").GetSection("AllowedOrigins").Value.Split(";");
builder.Services.AddCors(option =>{option.AddPolicy("CorsPolicy",builder => 
builder.WithOrigins(origins).AllowAnyMethod().AllowAnyHeader());
option.AddPolicy("AllowAll",builder => 
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());});

put MyConfig section in your appsettings.json with all your allowed origin urls.

CodePudding user response:

You should do 3 things in order to send CORS request to your Dotnet project using Angular

1- Enable CORS on the server side (All of the OPTIONS requests according to your URL should return 200 code with CORS-related headers (Allowed origins, Allowed headers)

See: here

2- Enable allowed origins in your Angular project (You should whitelist the origins you want send request to)

3- Be careful to use headers that are allowed in access-control-allow-headers while you are sending requests.

P.S: Don't use Wildcard for CORS options in your production environment. (It causes critical security problems)

  • Related