How to handel error “Response to preflight request doesn't pass access control check: The value of the...












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










share|improve this question

























  • stackoverflow.com/questions/51569826/…

    – Giollia
    Nov 28 '18 at 18:11











  • I'm pretty sure you want to pass the EnableCorsAttribute variable cors into the EnableCors method.

    – Jonathon Chase
    Nov 28 '18 at 18:12











  • @JonathonChase I dont understand how to do it?

    – user3223332
    Nov 28 '18 at 18:15











  • @user3223332 In your WebApiConfig.cs, try moving the declaration of cors to the top, then change config.EnableCors(); to config.EnableCors(cors);

    – Jonathon Chase
    Nov 28 '18 at 18:17











  • @JonathonChase Yes Thank you but it did not solved the probloem :/

    – user3223332
    Nov 28 '18 at 18:18
















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










share|improve this question

























  • stackoverflow.com/questions/51569826/…

    – Giollia
    Nov 28 '18 at 18:11











  • I'm pretty sure you want to pass the EnableCorsAttribute variable cors into the EnableCors method.

    – Jonathon Chase
    Nov 28 '18 at 18:12











  • @JonathonChase I dont understand how to do it?

    – user3223332
    Nov 28 '18 at 18:15











  • @user3223332 In your WebApiConfig.cs, try moving the declaration of cors to the top, then change config.EnableCors(); to config.EnableCors(cors);

    – Jonathon Chase
    Nov 28 '18 at 18:17











  • @JonathonChase Yes Thank you but it did not solved the probloem :/

    – user3223332
    Nov 28 '18 at 18:18














0












0








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










share|improve this question
















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







c# angular http asp.net-web-api2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 28 '18 at 18:19







user3223332

















asked Nov 28 '18 at 18:06









user3223332user3223332

546




546













  • stackoverflow.com/questions/51569826/…

    – Giollia
    Nov 28 '18 at 18:11











  • I'm pretty sure you want to pass the EnableCorsAttribute variable cors into the EnableCors method.

    – Jonathon Chase
    Nov 28 '18 at 18:12











  • @JonathonChase I dont understand how to do it?

    – user3223332
    Nov 28 '18 at 18:15











  • @user3223332 In your WebApiConfig.cs, try moving the declaration of cors to the top, then change config.EnableCors(); to config.EnableCors(cors);

    – Jonathon Chase
    Nov 28 '18 at 18:17











  • @JonathonChase Yes Thank you but it did not solved the probloem :/

    – user3223332
    Nov 28 '18 at 18:18



















  • stackoverflow.com/questions/51569826/…

    – Giollia
    Nov 28 '18 at 18:11











  • I'm pretty sure you want to pass the EnableCorsAttribute variable cors into the EnableCors method.

    – Jonathon Chase
    Nov 28 '18 at 18:12











  • @JonathonChase I dont understand how to do it?

    – user3223332
    Nov 28 '18 at 18:15











  • @user3223332 In your WebApiConfig.cs, try moving the declaration of cors to the top, then change config.EnableCors(); to config.EnableCors(cors);

    – Jonathon Chase
    Nov 28 '18 at 18:17











  • @JonathonChase Yes Thank you but it did not solved the probloem :/

    – user3223332
    Nov 28 '18 at 18:18

















stackoverflow.com/questions/51569826/…

– Giollia
Nov 28 '18 at 18:11





stackoverflow.com/questions/51569826/…

– Giollia
Nov 28 '18 at 18:11













I'm pretty sure you want to pass the EnableCorsAttribute variable cors into the EnableCors method.

– Jonathon Chase
Nov 28 '18 at 18:12





I'm pretty sure you want to pass the EnableCorsAttribute variable cors into the EnableCors method.

– Jonathon Chase
Nov 28 '18 at 18:12













@JonathonChase I dont understand how to do it?

– user3223332
Nov 28 '18 at 18:15





@JonathonChase I dont understand how to do it?

– user3223332
Nov 28 '18 at 18:15













@user3223332 In your WebApiConfig.cs, try moving the declaration of cors to the top, then change config.EnableCors(); to config.EnableCors(cors);

– Jonathon Chase
Nov 28 '18 at 18:17





@user3223332 In your WebApiConfig.cs, try moving the declaration of cors to the top, then change config.EnableCors(); to config.EnableCors(cors);

– Jonathon Chase
Nov 28 '18 at 18:17













@JonathonChase Yes Thank you but it did not solved the probloem :/

– user3223332
Nov 28 '18 at 18:18





@JonathonChase Yes Thank you but it did not solved the probloem :/

– user3223332
Nov 28 '18 at 18:18












1 Answer
1






active

oldest

votes


















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.






share|improve this answer
























  • It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10














Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525545%2fhow-to-handel-error-response-to-preflight-request-doesnt-pass-access-control-c%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









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.






share|improve this answer
























  • It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10


















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.






share|improve this answer
























  • It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10
















0












0








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.






share|improve this answer













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.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 30 '18 at 11:43









RAGHVENDER KATARIARAGHVENDER KATARIA

1515




1515













  • It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10





















  • It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10



















It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10







It didn't worked. I got error: Access to XMLHttpRequest at 'localhost:51492/api/GetGameResult' from origin '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 1 '18 at 13:10






















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525545%2fhow-to-handel-error-response-to-preflight-request-doesnt-pass-access-control-c%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Contact image not getting when fetch all contact list from iPhone by CNContact

count number of partitions of a set with n elements into k subsets

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks