【发布时间】:2017-10-10 07:02:28
【问题描述】:
我正在尝试使用 CORS 发出 POST 请求。
我有一个类可以在我的控制器内的方法上添加正确的响应头
using System;
using System.Web.Mvc;
public class AllowCrossSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");
base.OnActionExecuting(filterContext);
}
}
我就是这样用的
[AllowCrossSite]
public ActionResult GetReportParameters(string IdRapport)
但问题是当我尝试使用自定义标头发出 POST 请求以传递此特定内容类型时
'Content-Type': 'application/json; charset=utf-8'
我实际上得到了这些响应标头
所以即使我正确地进入了我的属性类,也好像没有对标题做任何事情。
这是我在 Angular 2 服务中的前端
const headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8' });
const options = new RequestOptions({ headers: headers , withCredentials: true });
const mock = {
name: 'TitreRegroupement1',
visible: false,
type: 'System.String',
value: 'Test'
};
// tslint:disable-next-line:max-line-length
const body = JSON.stringify({ idRapport: '00392024-d171-4f39-9c5c-97a51f53fd54', filtre: '', exportFormat: '', parameters: data });
return this.http.post('http://localhost:8080/ReportingViewer/ExportReport', body, options)
.map((response: Response) => {
return this.extractSingleData(response, Parameters);
})
.catch(this.handleError);
}
通过使用邮递员,声明没有问题,整个事情都可以正常运行,我可以毫无问题地从控制器内部的方法访问我的参数。
【问题讨论】:
-
不要忘记 ID 是关键字:{controller}/{action}/{id} 客户端 javascript: $http.get("../controller/action/" + ID).then (函数 (r) { $scope.item = r.data; });服务器端 C#.net: public JsonResult action(int ID){...}
标签: javascript asp.net-mvc angular asp.net-mvc-4 cors