0

I am trying to send Http POST request to web-api2 sever in my localhost. my client run on http://localhost:4200 and my server run on http://localhost/MemoryGameServer/api/Test. (Different Origin)

I have angular7 client code:

signUp(user: User){
        const body : any = {
            "FullName": "FullName",
            "UserName": "UserName",
            "Password": "Password",
            "Email": "Email",
            "UserId": 2
        }

        var headerOptions = new HttpHeaders({ 'Content-Type':'application/json' });

        return this.http.post(this.rootUrl + 'Test1', JSON.stringify(body), {
            headers: headerOptions,
            withCredentials: true
         });
    }   

and I have web api 2 server code:

public class clsTest
    {
        public string FullName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public int UserId { get; set; }
    }

    [RoutePrefix("api")]
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class MainController : ApiController
    {    
        [Route("Test1"), HttpPost]
        public IHttpActionResult Test1(clsTest data)
        {
            return Ok("OK!!");
        }
    }

my WebApiConfig.cs File: (Updated)

public static void Register(HttpConfiguration config)
    {
        EnableCorsAttribute cors = new EnableCorsAttribute("http://localhost:4200", "*", "*")
        {
            SupportsCredentials = true                
        };

        config.EnableCors(cors);

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

But I am getting error:

error

network tab

How can I fix it? I need to make http post request with Json object to the server.

Thank you!

UPDATE: I added this code to my web.config file:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

And now I am getting this error:

error

user3223332
  • 109
  • 7

1 Answers1

0

Below are the steps from Microsoft guidelines to "Enable CORS".

First, add the CORS NuGet package.

Install-Package Microsoft.AspNet.WebApi.Cors

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

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

Next, add the [EnableCors] attribute to the Controller class:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class MainController : ApiController
    {
        // Controller methods not shown...
    }
}

This allows cross-origin requests from WebClient, while still disallowing all other cross-domain requests.

Do not include a forward slash at the end of the origins URL.

Raghvender Kataria
  • 1,457
  • 7
  • 14
  • It didn't worked. I got error: Access to XMLHttpRequest at 'http://localhost:51492/api/GetGameResult' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. – user3223332 Dec 01 '18 at 13:10