I have 2 projects in ASP.Net Core 6.0. One is CMS(admin side) and other one is user side. I am trying to save a file through CMS project side ajax to user sider project.File saved successfully but i got an error
Access to XMLHttpRequest at 'https://localhost:7212/api/ManageAttachment/UploadminutesAttachment' from origin 'https://localhost:7056' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please help me out.
Ajax form CMS project
if (!$('#MinutesAndDecisions').valid()) {
e.preventDefault();
return false;
}
var files = $('#fileUpload').prop("files");
var url = '@Constants.FileUploadPath' + 'UploadminutesAttachment'
formData = new FormData();
formData.append("MyUploader", files[0]);
$.ajax({
type: 'POST',
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(repo) {
console.log(repo)
},
error: function() {
alert("Error occurs");
}
});
});
User Side function
[HttpPost]
[Route("UploadminutesAttachment")]
public UploadFileResponse UploadminutesAttachment(IFormFile MyUploader)
{
string FolderName = "Documents/minutes";
var response= UploadAttachment(MyUploader, FolderName).Result;
return new UploadFileResponse { Path=response.Path, Status=response.Status,Ext=response.Ext};
}
[HttpPost]
[Route("UploadAttachment")]
private async Task<UploadFileResponse> UploadAttachment(IFormFile MyUploader, string FolderName)
{
UploadFileResponse uploadFileResponse = new UploadFileResponse();
if (MyUploader != null)
{
var fileName = Path.GetFileName(MyUploader.FileName);
string ext = Path.GetExtension(MyUploader.FileName);
if (ext.ToLower() != ".pdf")
{
}
var filePath = Path.Combine(_hostingEnv.WebRootPath, FolderName, MyUploader.Name + ext);
using (var fileSteam = new FileStream(filePath, FileMode.Create))
{
await MyUploader.CopyToAsync(fileSteam);
}
uploadFileResponse.Status = true;
uploadFileResponse.Path = "/" + FolderName + "/" + MyUploader.Name + ext;
uploadFileResponse.Ext = "ext";
}
else
{
uploadFileResponse.Status = false;
uploadFileResponse.Path = "";
uploadFileResponse.Ext = "";
}
return uploadFileResponse;
}
Program.cs from CMS Project and user side project side is same
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
//var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var connectionString = Constants.DefaultConnectionString;
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
You need to configure Cross-Origin Requests in your user side:
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
//you can configure your custom policy
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
//.............
app.UseCors();
More details you can refer to this Documents;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With