【问题标题】:How to enable cross origin requests in ASP.NET MVC 4 on POST using Angular 2如何使用 Angular 2 在 POST 上启用 ASP.NET MVC 4 中的跨源请求
【发布时间】: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


【解决方案1】:

我找到了如何让它工作。首先,我应用向我提出的建议 sideshowbarker

if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase) &&
    Request.HttpMethod == "OPTIONS") {
    Response.Flush();
}

我在标题中遗漏了一些东西,我一直在做“*”,但最终使用这些参数它工作了

filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

对于那些对我的课程的最终形式感兴趣的人,这里是

using System;
using System.Web;
using System.Web.Mvc;

namespace Via.Client.WebMvc
{
    public class AllowCrossSiteAttribute : System.Web.Mvc.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", "Origin, X-Requested-With, Content-Type, Accept");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials", "true");

            if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
            {
                filterContext.HttpContext.Response.Flush();
            }

            base.OnActionExecuting(filterContext);
        }
    }
}

【讨论】:

  • 我很好奇为什么你更喜欢OnActionExecuting 而不是OnActionExecuted,因为如果选择后者你就不必Flush() ..
【解决方案2】:

您的前端 JavaScript 代码正在触发您的浏览器执行 CORS 预检 OPTIONS 请求。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

您需要更改服务器端代码以处理 OPTIONS 请求,例如添加:

if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OridinalIgnoreCase) &&
    Request.HttpMethod == "OPTIONS") {
    Response.Flush();
}

或查看https://stackoverflow.com/search?q=%5Basp.net-mvc%5D+%5Bcors%5D+options 了解许多其他相关答案。

【讨论】:

    【解决方案3】:

    您尝试过的代码都很好。这应该可行,但在您的情况下,这不起作用。

    我有一个参考资料给你,你必须检查一下

    Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

    【讨论】:

      猜你喜欢
      • 2017-02-26
      • 2015-05-19
      • 2016-08-12
      • 2019-02-22
      • 2015-07-05
      • 2017-10-04
      • 2015-10-29
      • 1970-01-01
      • 2016-11-23
      相关资源
      最近更新 更多