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:
In the WebAPIConfig.cs I have added:
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
But when I try to call it I receive:
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
do the following steps
Open the WebApiConfig.cs file in the App_Start folder of your project.
Add the following code to the Register method:
// Enable CORS globally
config.EnableCors();
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:
And then call it in the Register method:
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: