【问题标题】:Problem with cors and jquery while uploading a file上传文件时cors和jquery出现问题
【发布时间】:2021-08-04 02:52:19
【问题描述】:

我正在尝试将文件发送到我正在开发的系统上的 API。前端使用 jquery,后端使用 C# (.Net Core)。

我在后端启用了 CORS,一切正常。在 localhost 中上传工作正常,但是当我在实际服务器上尝试时,我收到了这个 CORS 错误。

我如何发送数据:

            $('#input-upload').change(function(event) {
                self.form = new FormData();
                self.form.append('arquivo', event.target.files[0]); 

                $.ajax(
                {
                    url: ControleDePagamentosModel.getUploadUrl(self.selected), 
                    data: self.form,
                    processData: false,
                    contentType: false,
                    type: 'POST'
                })
                .done(function(data)
                {
                    console.log(data);
                    if (data.error)
                    {
                        alert(data.message);
                    }
                    else if (data.message)
                    {
                        alert(data.message);
                    }
                })
                .fail(function()
                {
                    alert("Erro de comunicação com o servidor de dados!");
                });  
            });

服务器端点:

[HttpPost]
[Route("upload/{id}/{username}")]
public async Task<ResponseDTO> UploadFGTSAsync([FromForm] IFormFile arquivo, int id, string username)
{
    string path = "";

    if (arquivo !=null && arquivo.Length > 0)
    {
        ...

编辑:我的 CORS 配置:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting();
            services.AddCors(o => o.AddPolicy("apiPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.AddMvc().AddNewtonsoftJson(
                options => 
                {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                    options.SerializerSettings.MaxDepth = 1;
                }
            );
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "EmccampAPI", Version = "v1" });
            });

            services.Configure<IISOptions>(o =>
            {
                o.ForwardClientCertificate = false;
            });

            services.AddHttpClient();
            services.AddDbContext<DBCONTROLEMPContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ControlEmp")));
            //services.AddDbContext<RMContext>(options => options.UseSqlServer(Configuration.GetConnectionString("RM")));

            services.AddTransient<IConfigService, ConfigService>();
}

请注意,所有其他请求都有效。

【问题讨论】:

  • 你启用了哪些cors设置?!
  • 试试这个! $.ajax( { url: ControleDePagamentosModel.getUploadUrl(self.selected), data: self.form, processData: false, contentType: false, type: 'POST', "headers": { "accept": "application/json" , "Access-Control-Allow-Origin":"*" } })
  • 没用。请注意,所有其他请求都有效,我已从所有来源、方法和标头启用 CORS。我怀疑它与内容类型有关,但如果我不使用 contentType: false,它会给我一个 400 错误。
  • 嗨@ReisAlex,你试过我分享的解决方案了吗?

标签: c# jquery ajax asp.net-core


【解决方案1】:

我在后端启用了 CORS,一切正常。在 localhost 中上传工作正常,但是当我在实际服务器上尝试时,我收到了这个 CORS 错误。

请注意,所有其他请求都有效。

要解决此问题,请尝试将您的策略​​明确应用于该特定端点,如下所示。

[EnableCors("apiPolicy")]
[HttpPost]
[Route("upload/{id}/{username}")]
public async Task<ResponseDTO> UploadFGTSAsync([FromForm] IFormFile arquivo, int id, string username)
{
    //...

当问题发生时,请检查浏览器客户端是否使用大文件发出请求。如果请求超过the maxAllowedContentLength limitation,这将导致问题。您可以根据自己的实际情况尝试修改增加maxAllowedContentLength的值。

<requestFiltering>
    <requestLimits maxAllowedContentLength="90000000" />
</requestFiltering>

【讨论】:

    猜你喜欢
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 2012-10-16
    • 2017-11-30
    • 2016-01-28
    相关资源
    最近更新 更多