skip to Main Content

I am using web api with C# and calling it from a React app.
From the front end:

          const resp = await axios.post("http://localhost:26594/api/Member/Login", {
  member: user,
  sessionid,
});  

In the web api I have installed:
enter image description here

In the WebAPIConfig.cs I have added:

     var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

But when I try to call it I receive:
enter image description here
enter image description here

I then tried to add the web.config:

<httpProtocol>
      <customHeaders>
          <!-- Adding the following custom HttpHeader 
             will help prevent CORS from stopping the Request-->
          <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
  </httpProtocol>

and

<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

But nothing worked!

NOTE: I tried one GET method and working normally. POST method is not working.

2

Answers


  1. do the following steps

    1. Open the WebApiConfig.cs file in the App_Start folder of your project.

    2. Add the following code to the Register method:

      // Enable CORS globally
      config.EnableCors();

    3. Add the [EnableCors] attribute to your controller or controller method.

      [EnableCors(origins: "", headers: "", methods: "*")]
      public class MyController : ApiController
      {
      // Controller methods…
      }

    Note that the origins, headers, and methods parameters specify the CORS policy. In this example, the policy allows requests from any origin (*), with any headers, and with any HTTP method.

    Alternatively, you can create a separate class to configure the CORS policy and reference it in the Register method:

    public static class CorsConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
        }
    }
    

    And then call it in the Register method:

    public static void Register(HttpConfiguration config)
    {
        CorsConfig.Register(config);
       // Other configuration code...
    }
    
    Login or Signup to reply.
  2. If you are using ASP.NET Core, you need to enable CORS middleware in the Configure method of the Startup class. You can do this by adding the following code:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...
    
        app.UseCors(builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
    
        // ...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search