Post Angular Method

0
Hello, I'm developing an application using BackEnd as ASP.NET C #, and with Front Angular5! I'm doing a post method for the first time and it's not flowing well!

In the BackEnd I have a method as follows:

[HttpPost, Route("api/usuario/novo")]
public void Post([FromBody]Usuario usuario)
{
    _usuarioService.Adicionar(usuario);
}

That is, it is a Post method, which will receive a user and will add the same ...

In Angular I have the following requisition

inserindoUsuario(usuarios: any){
this.usuariosModel = {
     UsuarioId: null,
     Nome: usuarios.nome,
     Sobrenome: usuarios.sobrenome,
     Email: usuarios.email,
     Senha: usuarios.senha,
     Corretor: usuarios.corretor,
     Contrato: usuarios.contrato
 }

 let headers = new Headers();
 headers.append('Content-Type', 'application/json');

 this.Http.post('http://localhost:57301/api/usuario/novo', JSON.stringify(this.usuariosModel), { headers: headers })
 .subscribe(() => {
     console.log(this.usuariosModel);
 });
}

That is, I create a user, I add the Header of the request and I call Subscribe ... But in the browser console it presents the following error:

Failed to load http://localhost:57301/api/usuario/novo: Response to
preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed access. The
response had HTTP status code 405.

But my Header is already set up.

    
asked by anonymous 19.04.2018 / 07:19

2 answers

2

The error occurs because requests from source http://localhost:4200 are not enabled.

  

Origin ' link ' is therefore not allowed access.

To allow requests, both from specific sources and from any one, it is necessary to enable cors .

no nuget search for Microsoft.AspNet.WebApi.Cors or Package Manager Console run the command

Install-Package Microsoft.AspNet.WebApi.Cors

After this, in your class WebApiConfig add the following code.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

With config.EnableCors(new EnableCorsAttribute("*", "*", "*")); are released, in the first parameter all sources , in the second all headers and in the third all verbs .

You can read more about Cors in Microsoft Documentation

    
19.04.2018 / 18:33
0

Why this error occurred:

For security, the browser prevents a web page from making AJAX calls to another domain.

In this case, your Angular application runs on a different domain than your backend application.

How to resolve the problem:

Enabling% of

19.04.2018 / 18:30