1- In the Application_Start() Event of the global.asax file of a WCF project, all Header Settings were added. http://www.codeproject.com/Articles/845474/Enabling-CORS-in-WCF
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST,PUT,DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
2- CORS was enabled inside the WebApiConfig file http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
}
}
3- The [EnableCors] attribute on the action method of the controller was used to enable CORS for a single action.
public class VideoController : ApiController
{
[Route("PostComment")]
[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "POST")]
public HttpResponseMessage PostComment([FromBody] DTOUserComment comment)
{
HttpResponseMessage response = null;
try
{
IVideoDetails vdo = BaseServices.videoDetails();
vdo.UpdateComments(comment);
response = Request.CreateResponse(HttpStatusCode.OK, "Success");
}
catch (UnauthorizedAccessException ex)
{
response = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
}
catch (Exception ex)
{
response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
}
return response;
}
}
4- Data was posted from Angular js using $http.post()
$scope.publishComment = function () {
var myJSONData ={"UserName":"Asif"};
var req = {
method: "POST",
url: "http://localhost:55590/api/BaseAPI/postcomment",
data: myJSONData
};
$http(req).then(function(response){
alert("success");
},function(reason){
alert("error");
});
Before Adding CORS, the webapi response code showed "405 Method not Found" Error in Chrome browser: https://i.sstatic.net/udx20.jpg
After adding CORS inside WebAPi, the response status code changed to "200 OK", but the Request Header still showed "OPTION" instead of "POST" which caused data posting failures:
https://i.sstatic.net/uQwsf.jpg
Any assistance would be greatly appreciated. Thank you.