4

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

Since The FrontEnd and the BackEnd are different applications I have CORS setup, both for the Web API and in the Start.Auth.cs for the token bearer request.

The FronEnd is running on http://localhost:49850.

Now, for some code (this is all in the BackEnd)

Start.Auth.cs

The whole of the application resides behind a log-in form, so inside the Start.Auth.cs file, other than setting up the token-based authentication on the static Startup(), method I have a bit of middleware that adds the Access-Control-Allow-Origin header to the request on the one case where there is no token available yet: when we are requesting one.

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 the EnableCorsAttribute so that it is enable globally.

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

Uploading files

Everything works fine; I can perform GET and POST requests to the Web API without a problem, the problem comes when trying to upload images.

To upload to files I have an action method in an ASP.NET MVC controller called 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);
}

Calling the MVC controller

This is already part of The FrontEnd.

To call this method I use Aurelia's 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);
    });
}

And here's a call to the upload method above:

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

The Problem

All this works if I remove all CORS setup from WebApiConfig.cs, and in Startup.Auth.cs I substitute the call to the middleware for app.UseCors(CorsOptions.AllowAll);, so I know my code is ok, but as soon as I use the CORS setup described above, everything works except the call to http://localhost:64441/file/uploadImage, returning even a 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's mode to 'no-cors' to fetch the resource with CORS disabled.

The "funny" thing is that if I try calling that url with, for intance, REST Console I don't get a 404.

I've tried adding the [HttpOptions] attribute to the action method; I've tried creating ActionFilterAttributes as described here and here, and even setting uip CORS from within the web.config, but to no avail.

I know the problem is that FileController is a regular MVC Controller instead of a Web API controlle, but shouldn't it still be possible to get CORS working?

Community
  • 1
  • 1
Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101

1 Answers1

1

have you tried this

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

in ApplicationOAuthProvider.cs file

rashfmnb
  • 9,959
  • 4
  • 33
  • 44