C# 配置 CORS 问题

huangapple go评论74阅读模式
英文:

C# problems with configure cors

问题

I have been trying for several hours over the last few days to fix my cors problems. My JS is running in the browser to call my currently locally running endpoint.

我已经试了好几个小时,在过去的几天里一直在尝试解决我的跨域问题。我的JavaScript代码正在浏览器中运行,用于调用我的本地运行的端点。

I am having Cors problems and I have tried several things to get on with my local development.

我遇到了跨域问题,尝试了几种方法来继续我的本地开发。

I have read in some articles and Stackoverflow post that chrome can not handling cors ob localhost so I have also tried this.

我在一些文章和Stackoverflow帖子中读到,Chrome不能处理本地主机上的跨域问题,所以我也尝试了这个。

open -a Google\ Chrome --args --disable-web-security --user-data-dir

但这并没有起作用。其他浏览器也是如此。

Here is my C# Code.

这是我的C#代码。

using Amazon;
using Amazon.DynamoDBv2;
using Customers.Api.Contracts.Responses;
using Customers.Api.Repositories;
using Customers.Api.Services;
using Customers.Api.Validation;
using FastEndpoints;
using FastEndpoints.Swagger;

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("127.0.0.1:5000", "127.0.0.1:5001", "http://127.0.0.1:5000", "http://localhost:5000"
                "http://127.0.0.1:5001").AllowAnyMethod().AllowAnyHeader();
        });
});

builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);
builder.Services.AddFastEndpoints();
builder.Services.AddSwaggerDoc();
builder.Services.AddSingleton<IAmazonDynamoDB>(_ => new AmazonDynamoDBClient(RegionEndpoint.EUCentral1));
builder.Services.AddSingleton<ICustomerRepository>(provider =>
    new CustomerRepository(provider.GetRequiredService<IAmazonDynamoDB>(),
        config.GetValue<string>("Database:TableName")));
builder.Services.AddSingleton<ICustomerService, CustomerService>();
var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);
app.UseMiddleware<ValidationExceptionMiddleware>();
app.UseFastEndpoints(x =>
{
    x.ErrorResponseBuilder = (failures, _) =>
    {
        return new ValidationFailureResponse
        {
            Errors = failures.Select(y => y.ErrorMessage).ToList()
        };
    };
});
app.UseOpenApi();
app.UseSwaggerUi3(s => s.ConfigureDefaults());
app.Run();

and this is my Javascript code

这是我的JavaScript代码

var payload = {
              event: eventData,
              signupType: signupType,
              name: name,
              email: email,
              birthdate: birthdate,
              gender: gender,
              orientation: orientation,
              partner: {
                name: partnerName,
                email: partnerEmail,
                birthdate: partnerBirthdate,
                gender: partnerGender,
                orientation: partnerOrientation,
              }
            };
          
            
            fetch('http://127.0.0.1:5000/customers', {
              method: 'POST',
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify(payload)
            })
            .then(function(response) {
              if (!response.ok) {
                throw an Error('Network response was not ok');
              }
              return response.json();
            })
            .then(function(data) {
              console.log('Success:', data);
            })
            .catch(function(error) {
              console.error('Error:', error);
            });
          });

This are my error messages...
C# 配置 CORS 问题

这是我的错误消息...
C# 配置 CORS 问题

I haven't any idea what I can try now. And I think about to rewrite this piece in node.js and express because there I haven't normally problems with configure the cors rules...

我现在没有任何想法可以尝试什么。我考虑将这一部分重写为Node.js和Express,因为在那里我通常不会遇到配置CORS规则的问题...

英文:

I have been trying for several hours over the last few days to fix my cors problems. My JS is running in the brower to call my currently locally running endpoint.
I am having Cors problems and I have tried several things to get on with my local development.
I have read in some articles and Stackoverflow post that chrome can not handling cors ob localhost so I have also tried this.

open -a Google\ Chrome --args --disable-web-security --user-data-dir

But it did not work. Also with other browsers.

Here is my C# Code.

using Amazon;
using Amazon.DynamoDBv2;
using Customers.Api.Contracts.Responses;
using Customers.Api.Repositories;
using Customers.Api.Services;
using Customers.Api.Validation;
using FastEndpoints;
using FastEndpoints.Swagger;

var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
var  MyAllowSpecificOrigins = &quot;_myAllowSpecificOrigins&quot;;
builder.Services.AddCors(options =&gt;
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
        builder =&gt;
        {
            builder.WithOrigins(&quot;127.0.0.1:5000&quot;,&quot;127.0.0.1:5001&quot;, &quot;http://127.0.0.1:5000&quot;,&quot;http://localhost:5000&quot;
                &quot;http://127.0.0.1:5001&quot;).AllowAnyMethod().AllowAnyHeader();
        });
});

builder.Services.AddAWSLambdaHosting(LambdaEventSource.HttpApi);
builder.Services.AddFastEndpoints();
builder.Services.AddSwaggerDoc();
builder.Services.AddSingleton&lt;IAmazonDynamoDB&gt;(_ =&gt; new AmazonDynamoDBClient(RegionEndpoint.EUCentral1));
builder.Services.AddSingleton&lt;ICustomerRepository&gt;(provider =&gt;
    new CustomerRepository(provider.GetRequiredService&lt;IAmazonDynamoDB&gt;(),
        config.GetValue&lt;string&gt;(&quot;Database:TableName&quot;)));
builder.Services.AddSingleton&lt;ICustomerService, CustomerService&gt;();
var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);
app.UseMiddleware&lt;ValidationExceptionMiddleware&gt;();
app.UseFastEndpoints(x =&gt;
{
    x.ErrorResponseBuilder = (failures, _) =&gt;
    {
        return new ValidationFailureResponse
        {
            Errors = failures.Select(y =&gt; y.ErrorMessage).ToList()
        };
    };
});
app.UseOpenApi();
app.UseSwaggerUi3(s =&gt; s.ConfigureDefaults());
app.Run();

and this is my Javascript code

var payload = {
              event: eventData,
              signupType: signupType,
              name: name,
              email: email,
              birthdate: birthdate,
              gender: gender,
              orientation: orientation,
              partner: {
                name: partnerName,
                email: partnerEmail,
                birthdate: partnerBirthdate,
                gender: partnerGender,
                orientation: partnerOrientation,
              }
            };
          
            
            fetch(&#39;http://127.0.0.1:5000/customers&#39;, {
              method: &#39;POST&#39;,
              headers: {
                &quot;Content-Type&quot;: &quot;application/json&quot;
              },
              body: JSON.stringify(payload)
            })
            .then(function(response) {
              if (!response.ok) {
                throw new Error(&#39;Network response was not ok&#39;);
              }
              return response.json();
            })
            .then(function(data) {
              console.log(&#39;Success:&#39;, data);
            })
            .catch(function(error) {
              console.error(&#39;Error:&#39;, error);
            });
          });
          

This are my error messages...
C# 配置 CORS 问题

I haven't any idea what I can try now. And I think about to rewrite this piece in node.js and express because there I haven't normally problems with configure the cors rules...

答案1

得分: 1

根据您的浏览器错误,看起来源是'null'。因此,我建议您尝试将字符串"null"添加到添加.WithOrigins参数时的源列表中。

问题在于您已将请求目标的IP/端口添加到其中(您的.NET应用程序),而不是请求的来源,而在您的情况下未找到来源并设置为null。

我可以问一下,您正在从哪个网站调用您的JavaScript的地址是什么?而且,当您将字符串"*"添加到源列表时,是否有效?请记住,您不希望在生产级环境设置中使用这个。

英文:

Based on the error from your browser it looks like the origin is 'null'. So, what I would suggest you try is adding the string "null" to the list of origins when you add the .WithOrigins parameter.

The problem is that you've added the IP/Ports of the request destination in there (your .NET App) and not the origin of the request which in your case is not being found and is being set to null.

Can I ask what the address is of the site you're calling your Javascript from? Also, does it work when you add the string "*" to the list of origins? Keep in mind you don't want this in a production level environment setting.

huangapple
  • 本文由 发表于 2023年6月26日 22:45:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定