【问题标题】:Enable CORS in Angular 6 and ASP.net在 Angular 6 和 ASP.net 中启用 CORS
【发布时间】:2019-11-18 21:00:21
【问题描述】:

我正在尝试从我的 Angular 6 应用程序向发送电子邮件的 API 发送 POST 请求。

我使用邮递员测试了该请求并且它有效,但是当我在我的 Angular 应用程序中执行 POST 请求时,我的控制台中出现错误。

我在 Angular 应用中的功能:

sendMail(formBody: string): any {
    //let url = this.config.origin + "/api/SendEmail";
    let url = "http://localhost:49561/api/SendEmail";
    let headers = new HttpHeaders();
    headers = headers.append('Content-Type', 'application/json');

    return this.httpClient.post(url, formBody, { headers })
      .pipe(map(res => {
        return res;
      })).toPromise();
  }

我已将以下内容添加到我的 API:

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Enable Cors
            config.EnableCors();
            ...
    [EnableCors(origins: "http://localhost:4200/contact", headers: "*", methods: "*")]
    public class ContactFormsController : ApiController
    {
       ...

这些是我在控制台中收到的警告和错误:

“跨域请求被阻止:同源策略不允许读取位于http://localhost:49561/api/SendEmail 的远程资源。(原因:CORS 标头‘Access-Control-Allow-Origin’缺失)。”

“跨域请求被阻止:同源策略不允许读取位于http://localhost:49561/api/SendEmail 的远程资源。(原因:CORS 请求未成功)。”

“错误错误:“未捕获(承诺):HttpErrorResponse:{“headers”:{“normalizedNames”:{},“lazyUpdate”:null,“headers”:{}},“status”:0, statusText":"未知错误","url":null,"ok":false,"name":"HttpErrorResponse","message":"(未知 url)的 Http 失败响应:0 未知错误","error" :{"isTrusted":true}}""

编辑: 我在 Web.config 中添加了以下内容:

         <httpProtocol>
                <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                </customHeaders>
         </httpProtocol>

现在我收到此错误,而不是“缺少‘Access-Control-Allow-Origin’”:

跨域请求被阻止:同源策略不允许读取位于http://localhost:49561/api/SendEmail 的远程资源。 (原因:CORS 预检通道未成功)

编辑:

删除“内容类型:应用程序/json”后。我在控制台中收到此错误:

错误错误:“未捕获(承诺):HttpErrorResponse:{“headers”:{“normalizedNames”:{},“lazyUpdate”:null},“status”:500,“statusText”:“内部服务器错误” ,"url":"http://localhost:49561/api/SendEmail","ok":false,"name":"HttpErrorResponse","message":"http://localhost:49561/api/SendEmail 的 Http 失败响应:500 内部服务器错误","error":{" Message":"发生错误。","ExceptionMessage":"指定的策略来源 'http://localhost:4200/contact' 无效。它不能包含路径、查询或片段。","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Cors.EnableCorsAttribute.ValidateOrigins(IList`1 origins)\r\ n 在 System.Web.Http.Cors.EnableCorsAttribute.GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancelToken)\r\n 在 System.Web.Http.Cors.CorsMessageHandler.d__8.MoveNext()\r\n--- 堆栈结束从先前引发异常的位置跟踪 ---\r\n System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\ n 在 System.Web.Http.Cors.CorsMessageHandler.d__5.MoveNext()\r\n--- 从先前引发异常的位置结束堆栈跟踪 ---\r\n 在 System.Runtime.CompilerServices.TaskAwaiter .ThrowForNonSuccess(任务任务)\r\n 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\n 在System.Web.Http.Cors.CorsMessageHandler.d__4.MoveNext()"}}"

【问题讨论】:

  • 您是否为 CORS 安装了 Nuget 包?
  • @UbiquitousDevelopers 是的,我有
  • 在下面查看我的答案

标签: c# asp.net asp.net-mvc angular


【解决方案1】:

转到您的 App_start 文件夹并打开 WebApiConfig.cs

添加以下行:

 EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET, POST, PUT, DELETE, OPTIONS");
 config.EnableCors(cors);

最终代码:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "GET, POST, PUT, DELETE, OPTIONS");
            config.EnableCors(cors);
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }

您可以在 Origins 中替换 * from localhost:4200

【讨论】:

  • 我刚试过。我仍然遇到与以前相同的错误。我还在 API 中的 SendMail() 函数上设置了一个断点,但它甚至没有到达那里。
  • 我建议删除 content-type : application/json.你不需要添加它
  • 我在删除内容类型后更新了问题:application/json
【解决方案2】:

使用属性(所有浏览器尚不支持对 Access-Control-Allow-Methods 使用通配符。)

[EnablCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE, OPTIONS")]

在全球范围内

您必须在 global.asax 中单独处理“OPTIONS”方法,因为浏览器会向服务器发送飞行前请求

protected void Application_BeginRequest()
{
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
        HttpContext.Current.Response.End();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 2019-03-03
    • 2015-10-29
    • 2020-09-02
    • 1970-01-01
    • 2017-02-08
    • 2020-09-13
    • 2019-08-22
    相关资源
    最近更新 更多