从 Angular 向 .Net 发送 POST API 时出现 CORS 错误

问题描述 投票:0回答:1

我正在尝试从 Angular 向我的 dot net Framework api 代码发送一个 POST API,但它给了我 CORS 错误。我已经确定了两种情况。

案例1

当我使用下面的角度服务时,它会给出以下错误(提到的屏幕截图)。我有一个 POST api,我正在传递数据并在 .net 中接受相同的操作。

角度服务


startStopService(data:any,options?:any):Observable<any>{

    const headers = new HttpHeaders({

       'Content-Type':  'application/json'

    });

    console.log("data type" , typeof(JSON.stringify(data)))

    return this.http.post<any>(this.url+"action",data,{headers});

  }

上面是我的 Angular 服务,下面是我在发送 POST api 数据时遇到的错误的屏幕截图。

Angular Header Error

Angular Header Error 2

案例2

当我更改角度服务中的标头内容时,我没有收到 CORS 错误。但是,我收到另一个错误,暗示“机器名称无效”。即使机器名称是从 API 的 web.config 传递的,并且它具有准确的值。 我的预感是,当将数据从 Angular 传递到 .net api 时,它会以 JSON 字符串形式发送。但是,api 代码无法将其解析为正确的格式。以下是更改后的角度服务和屏幕截图。


startStopService(data:any,options?:any):Observable<any>{

    const headers = new HttpHeaders({

  

      'Content-Type':  'application/x-www-form-urlencoded;charset=utf-8'

    });

    console.log("data type" , typeof(JSON.stringify(data)))

    return this.http.post<any>(this.url+"action",JSON.stringify(data),{headers});

  }

Angular CORS Error

我已附上我的 webapi.config.cs 文件以供参考。


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
using System.Web.Http;
using System.Web.Http.Cors;
//using Microsoft.AspNetCore.Cors;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

         
                     
            config.EnableCors(new EnableCorsAttribute("http://localhost:4200", "*", "GET, POST, OPTIONS, PUT, DELETE"));
            // Register Preflight Request Handler
            config.MessageHandlers.Add(new PreflightRequestsHandler());

            
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

        public class PreflightRequestsHandler : DelegatingHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                if (request.Method == HttpMethod.Options)
                {
                    var response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");
                    response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                    response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
                    return Task.FromResult(response);
                }

                return base.SendAsync(request, cancellationToken);
            }
        }
    }
}

网络API

<configuration>
<appSettings>
<add key="ServerName" value="Avinash"/>
<add key="services" value="AxInstSV,AppHostSvc"/>
</appSettings></configuration>

在配置中,我尝试使用自定义标头并将值指定为 Access-Control-Allow-Origin ="*",但它也不起作用。

注意:我的 api 在 .net 4.7.2 框架中,而 Angular 在 17 中。 Microsoft.aspnet.webapi.core -->5.2.7 Microsoft.aspnet.webapi.cors -->5.2.7

在上面的 webapiconfig.cs 文件中,我尝试仅使用 * 而不是指定的,但这也不起作用。

如果您需要更多详细信息,请告诉我并帮助我。

c# asp.net angular cors http-headers
1个回答
0
投票
CORS Error:

If this is a CORS error, it indicates that your frontend (Angular) is making a request to a server that has not allowed cross-origin requests from your domain. This would need to be resolved by configuring the backend server to allow requests from the domain where your frontend is hosted.
Solution:

Ensure that CORS is properly configured in your backend API to allow requests from your frontend. In ASP.NET Core, you can enable CORS in Startup.cs like this:

services.AddCors(options =>
{
    options.AddPolicy("AllowOrigin", builder =>
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader());
});

Apply the CORS policy in the middleware:

app.UseCors("AllowOrigin");

400 Bad Request:

The error message you're seeing, MachineName value is invalid, is likely being returned from your backend. It suggests that the data being passed might be in the wrong format or missing a required field.
Solution:

Ensure that the data object contains the correct structure that the API expects.
Instead of using 'application/x-www-form-urlencoded', you may want to try 'application/json', especially if your backend expects JSON data:
typescript
Copy code
const headers = new HttpHeaders({
  'Content-Type': 'application/json'
});`enter code here`

return this.http.post<any>(this.url + "action", data, { headers });
Debugging the Data:

The console log statement shows you are logging the type of the data being sent. Check the console to see if data is in the expected format. If not, adjust the structure before sending it in the request.
© www.soinside.com 2019 - 2024. All rights reserved.