CORS on the Web API and MVC 5 Controller: Uploading Images Using Fetch and FormData

I have an application that has front and rear ends running on different .NET projects. The front end is an Aurelia web application running on ASP.NET 5. This Aurelia app (now The FrontEnd ) gets all the data from the Web API 2 / MVC 5 app (now BackEnd ).

Since FrontEnd and BackEnd are different applications, I have a CORS setting for both the web API and the Start.Auth.csrequest for token carrier.

FronEnd works on http://localhost:49850.

Now, for some code (all in BackEnd)

Start.Auth.cs

The entire application is behind the login form, so inside the file Start.Auth.cs, in addition to setting up authentication based on tokens in the method static Startup(), I have some middleware that adds Access-Control-Allow-Originto the request when there is no token yet: when we request it.

public void ConfigureAuth(IAppBuilder app)
{
    app.Use(async (context, next) =>
    {
        if (context.Request.Path.Value.Equals("/token"))
            context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:49850" });
        await next();
     });

     app.UseCors(CorsOptions.AllowAll);
     app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

WebApiConfig.cs

Here I just added EnableCorsAttributeto enable it globally.

var enableCors = new EnableCorsAttribute("http://localhost:49850", "*", "*");
config.EnableCors(enableCors);

Upload files

Everything is working fine; I can execute queries GETand POSTin web-API without any problems, the problem arises when you try to download the images.

To upload files, I have an action method in the ASP.NET MVC controller named FileControler.

Filecontroller.cs

[HttpPost]
public ActionResult UploadImage(string id, string name = "")
{
    var files = (from string fileName in Request.File
                 select Request.Files[fileName]
                 into file
                 where file != null
                 select DoSomethingWithTheFile(file, id)).ToList();
    // ...

    return Json(arrayWithFileUrls);
}

Call MVC

This is already part of FrontEnd.

, Aurelia Fetch Client:

upload(url, data, files) {
    let formData = new FormData();
    for (let key of Object.keys(data)) {
        formData.append(key, data[key]);
    }
    for (let i = 0; i < files.length; i++) {
        formData.append(`files[${i}]`, files[i]);
    }

    return this.http.fetch(url, {
        method: "POST",
        body: formData,
        headers: {
            cmsDatabase: sessionStorage["cmsDatabase"]
        }
    }).then(response => {
        return response.json();
    }).catch(error => {
        console.log(error);
    });
}

upload :

// files comes from an <input type="file" />
upload("http://localhost:64441/file/uploadImage", { id: id }, files) 
     .then((uploadedPhotos) => {
          // do something with those file urls...
 }); 

, CORS WebApiConfig.cs, Startup.Auth.cs app.UseCors(CorsOptions.AllowAll);, , , CORS , , http://localhost:64441/file/uploadImage, 404:

Fetch API cannot load http://localhost:64441/file/uploadForSku. 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' 
header is present on the requested resource. 
Origin 'http://localhost:49850' is therefore not allowed access. 
The response had HTTP status code 404. If an opaque response serves your needs, 
set the request mode to 'no-cors' to fetch the resource with CORS disabled.

"", url, intance, REST Console, 404.

[HttpOptions] ; ActionFilterAttributes, , uip CORS web.config, .

, , FileController MVC-, -API, CORS ?

+4
1

 context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

ApplicationOAuthProvider.cs

+1

All Articles