c# - 在 Angular 6 和 ASP.net 中启用 CORS

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

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

我用 postman 测试了请求并且它有效,但是当我在我的 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
    {
       ...

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

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49561/api/SendEmail. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49561/api/SendEmail. (Reason: CORS request did not succeed)."

"ERROR Error: "Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}""

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

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

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

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:49561/api/SendEmail. (Reason: CORS preflight channel did not succeed)

编辑:

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

ERROR Error: "Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":500,"statusText":"Internal Server Error","url":"http://localhost:49561/api/SendEmail","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:49561/api/SendEmail: 500 Internal Server Error","error":{"Message":"An error has occurred.","ExceptionMessage":"The specified policy origin 'http://localhost:4200/contact' is invalid. It must not contain a path, query, or fragment.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Cors.EnableCorsAttribute.ValidateOrigins(IList`1 origins)\r\n at System.Web.Http.Cors.EnableCorsAttribute.GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Cors.CorsMessageHandler.d__8.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Cors.CorsMessageHandler.d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Cors.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

关于c# - 在 Angular 6 和 ASP.net 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56950277/

相关文章:

c# - 来自 HRESULT : 0x8001010E (RPC_E_WRONG_THREAD) 的 Windows Phone 异常

c# - 如何使用 C# 更改打印机的端口名称

asp.net - 查找控件 Asp.net

asp.net-mvc - 如何将 ASP.NET MVC 应用程序发布到免费主机

c# - SignalR 客户端未定义

c# - 验证密码大小写

asp.net - CSS 不加载

asp.net-mvc - 是否可以在 session 中为当前用户的角色使用 key ?

asp.net-mvc - Kendo 网格模板中的 For 循环

c# - 在 .NET 中创建 ZIP 存档的最佳/最简单方法是什么?