gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 15:33:27 32 4
gpt4 key购买 nike

1- 在应用程序中添加了所有 header 设置WCF 项目的 global.asax 文件的 _Start() 事件。 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,请在 Controller 的操作方法上修饰 [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 之前,webapi 响应代码在 Chrome 浏览器中是“405 Method not Found”错误: enter image description here

在 WebAPI 中添加 CORS 后,响应状态代码为“200 OK”,但请求 header 仍然显示“OPTION”而不是“POST”,并且数据发布失败:

enter image description here

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

最佳答案

我好像通过修改header信息修改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();
}
}

此外,我的 Angular 代码看起来是这样的:

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

关于javascript - 使用 Angular JS $http.post() 将 json 数据发布到 WCF REST 在 Chrome 中失败但在 IE 中成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32189654/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com