繁体   English   中英

在 Angular 6 和 ASP.net 中启用 CORS

[英]Enable CORS in Angular 6 and ASP.net

我正在尝试从我的 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":"Http 失败响应(未知 url):0 未知错误","error":{" isTrusted":true}}""

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

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

现在我收到这个错误而不是“'Access-Control-Allow-Origin' missing”:

跨域请求被阻止:同源策略不允许读取位于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 Internal Server Error","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 cancelationToken)\\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 n 在 System.Web.Http.Cors.CorsMessageHandler.d__5.MoveNext()\\r\\n--- 从上一个抛出异常的位置的堆栈跟踪结束 ---\\r\\n 在 System.Runtime.CompilerServices.TaskAwaiter .ThrowForNonSuccess(Task task)\\r\\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\\r\\n at System.Web.Http.C ors.CorsMessageHandler.d__4.MoveNext()"}}"

转到您的 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

使用属性(所有浏览器尚不支持 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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM