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:
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: