繁体   English   中英

使用Angular JS $ http.post()向WCF REST发布json数据在Chrome中失败但在IE中成功

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

1-添加了应用程序内的所有标头设置_Start()WCF项目的global.asax文件的事件。 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- WebApiConfig文件中的已启用的cors 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-要为单个操作启用CORS,请在控制器的操作方法上修饰[EnableCors]属性。

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-从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"); 
});

在添加CORS之前,Chrome浏览器中的webapi响应代码为“405 Method not found”错误: 在此输入图像描述

在WebAPi中添加CORS后,响应状态代码为“200 OK”,但仍然请求标题显示“OPTION”但不显示“POST”,数据发布失败:

在此输入图像描述

非常感谢任何帮助。谢谢。

我似乎通过修改头信息修改Global.asax.cs来解决这个问题:

    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();
        }
    }

另外我的角度代码看起来像这样:

        $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);
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM