Asif Iqbal
Asif Iqbal

Reputation: 543

Posting json data using Angular JS $http.post() to WCF REST fails in Chrome but success in IE

1- Added all Header Setting inside Application _Start() Event of global.asax file of WCF project. 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- Enabled cors inside 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- To enable CORS for a single action, decorated the [EnableCors] attribute on the action method of controller.

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- Posting data from Angular js $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 ,webapi response code was "405 Method not Found" Error in Chrome browser: enter image description here

After adding CORS inside WebAPi response status code is "200 OK" but still Request Header shows "OPTION" but not "POST" and data posting fails:

enter image description here

Any Help is greatly appreciated.Thanks.

Upvotes: 3

Views: 1633

Answers (1)

fadi mikael
fadi mikael

Reputation: 21

I seem to have solved this issue by modifying the Global.asax.cs by modifying the header information:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Api-Version");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

In addition my angular code looks as such:

        $http.defaults.useXDomain = true;
        delete $http.defaults.headers.common['X-Requested-With'];

        var req = {
            url: BASEURL + 'Login',
            method: "POST",
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            },
            data: {
                userName: username, password: password, isPersistent: true
            }
        }

        $http(req)
            .success(function (response) {
                console.log(response);
                callback(response);
        });

Upvotes: 1

Related Questions