【发布时间】: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