I have tried 2 methods of calling the web api from a Typescript component: XMLHttpRequest and HttpRequest. Both have the exact same effect.
I can reach the web api if I do not send the file as a parameter in the .send() command. Sending the file results in this message in the browser:
Typescript:
note: environment.fileUploadX_Url is "https://localhost:44387/api/UploadFile/UploadFile"
export class FileService {
private url = environment.fileUploadX_Url;// + environment.fileUploadLoc;
constructor(private http: HttpClient) {
}
upload(file: File) {
var xhr = this.createCORSRequest('POST', this.url);
xhr.upload.onprogress = function (event) {
console.log('Uploaded ${event.loaded} of ${event.total}');
};
const fd = new FormData();
fd.append('resultFile', file);
xhr.send(fd);//
//const req = new HttpRequest('POST', this.url, fd);
//req.headers.append('Access-Control-Allow-Origin', environment.serverUrl);
//this.http.request(req).subscribe(result => { });
}
createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data;");
return xhr;
}
}
Web api:
namespace Namespace.Controllers
{
[EnableCors("ThePolicy")]
[Route("api/[controller]")]
[ApiController]
public class UploadFileController : ControllerBase
{
[EnableCors("ThePolicy")]
[HttpPost, DisableRequestSizeLimit, Route("UploadFile")]
public async Task UploadFile()
{
var files = Request.Form.Files;
HttpResponseMessage res = new HttpResponseMessage();
var filePath = "/Logs";
}
}
}
Here is my api Startup code:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCors(o => o.AddPolicy("ThePolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
ConfigureServicesModule<DB_Dev_Phase2Context>.Register(services, Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseMvc();
ConfigureModule.Configure(app, env, Configuration);
app.UseCors("ThePolicy");
}
}
