【发布时间】:2015-11-18 07:27:23
【问题描述】:
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 之前,webapi 响应代码是 Chrome 浏览器中的“405 Method not Found”错误:
在 WebAPi 中添加 CORS 后,响应状态码为“200 OK”,但 Request Header 仍显示“OPTION”但未显示“POST”且数据发布失败:
非常感谢任何帮助。谢谢。
【问题讨论】:
-
您在“Application_BeginRequest”中的代码与您的“EnableCors”属性相结合正在生成重复的标头。
标签: javascript angularjs wcf asp.net-web-api