I have a Blazor server solution with separate projects for the UI and API. When the Upload component is configured to use a controller in the API project to handle the save function I get the error seen in the attached file 'Screenshot 2025-02-26 132709' but the file is successfully uploaded. If I copy the same controller to the UI project the error goes away see 'Screenshot 2025-02-26 132538'.
to get the save function to work with the API at all I had to add the below HTTP options section to the API program.cs
app.Use(async (context, next) => { if (context.Request.Method == HttpMethods.Options) { context.Response.Headers.Add("Allow", "GET, POST, PUT, OPTIONS"); context.Response.Headers.Add("Access-Control-Allow-Origin", "https://localhost:7053"); context.Response.StatusCode = (int)HttpStatusCode.OK; return; } await next.Invoke(); });
Upload component:
<TelerikUpload SaveUrl="@saveURL"
RemoveUrl="https://localhost:7121/api/DocumentUpload/remove"
MaxFileSize="@MaxFileSize"
/>
Controller:
using DocumentFormat.OpenXml.Drawing;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DocumentUploadController : ControllerBase
{
public IWebHostEnvironment HostingEnvironment { get; set; }
public DocumentUploadController(IWebHostEnvironment hostingEnvironment)
{
HostingEnvironment = hostingEnvironment;
}
[HttpPost("save")]
public async Task<IActionResult> Save(IFormFile files) // "files" matches the Upload SaveField value
{
if (files != null)
{
try
{
// save to wwwroot - Blazor Server only
//var rootPath = HostingEnvironment.WebRootPath;
// save to Server project root - Blazor Server or WebAssembly
var rootPath = HostingEnvironment.ContentRootPath;
var newFolder = Guid.NewGuid().ToString();
System.IO.Directory.CreateDirectory(rootPath + newFolder);
var saveLocation = System.IO.Path.Combine(rootPath + newFolder, files.FileName);
using (var fileStream = new FileStream(saveLocation, FileMode.Create))
{
await files.CopyToAsync(fileStream);
}
}
catch (Exception ex)
{
Response.StatusCode = 500;
await Response.WriteAsync($"Upload failed.");
}
}
return new OkResult();
}
[HttpPost("remove")]
public async Task<IActionResult> Remove([FromForm] string files) // "files" matches the Upload RemoveField value
{
if (files != null)
{
try
{
// delete from wwwroot - Blazor Server only
var rootPath = HostingEnvironment.WebRootPath;
// delete from Server project root - Blazor Server or WebAssembly
//var rootPath = HostingEnvironment.ContentRootPath;
var fileLocation = System.IO.Path.Combine(rootPath, files);
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
}
catch (Exception ex)
{
Response.StatusCode = 500;
await Response.WriteAsync($"Delete failed.");
}
}
return new EmptyResult();
}
}
}
Any ideas? Have I missed something I need to setup in the API program.cs?