Metodo Post Angular

Asked

Viewed 312 times

0

Hello, I am developing an application using as Backend ASP.NET C#, and with front Angular5! I’m doing a post method for the first time and it’s not flowing well!

In 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...

At Angular I have the following request

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, mount the request header and call the Subscribe... However in the browser console shows 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 configured..

  • 1

    Give a search on how to leave Cors in your backend

2 answers

3


Error occurs because source requests are not enabled http://localhost:4200.

Origin 'http://localhost:4200' is therefore not allowed access.

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

in the nuget look for Microsoft.AspNet.WebApi.Cors or by Package Manager Console execute the command

Install-Package Microsoft.AspNet.WebApi.Cors

After that, 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 the config.EnableCors(new EnableCorsAttribute("*", "*", "*")); are released, in the first parameter all origins, in the second all headers and in the third, all the verbs.

You can read more about Cors in Microsoft documentation

0

Why did this error occur:

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

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

How to solve the problem:

Enabling Cross Origin Resource Sharing (CORS) you’ll be able to make that call.

I have already implemented CORS for an application Asp.Net CORE, but searching for the case of an Asp.Net MVC application (credits: source in English):

Create a new attribute:

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Add the attribute to your action:

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

In the reference link you will examples to enable CORS in Asp.Net MVC and Asp.Net Apis applications. Remembering that you have the option to solve via package Microsoft.AspNet.Webapi.Cors also (as @Barbetta reply).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.