【问题标题】:CORS on Web API and MVC 5 Controller: Upload images with fetch and FormDataWeb API 和 MVC 5 控制器上的 CORS:使用 fetch 和 FormData 上传图像
【发布时间】:2016-06-24 08:37:17
【问题描述】:

我有一个应用程序,它的前端和后端在不同的 .NET 项目上运行。 前端是一个在 ASP.NET 5 上运行的 Aurelia Web 应用程序。这个 Aurelia 应用程序(从现在开始前端)从 Web API 2/MVC 5 应用程序(此后, 后端)。

由于 FrontEnd 和 BackEnd 是不同的应用程序,我为 Web API 和 Start.Auth.cs 设置了 CORS,用于令牌承载请求。

FronEnd 在http://localhost:49850 上运行。

现在,对于一些代码(这都在后端)

Start.Auth.cs

整个应用程序驻留在登录表单后面,因此在Start.Auth.cs 文件中,除了在static Startup() 上设置基于令牌的身份验证之外,我还有一些中间件添加@ 987654330@ 标头在没有可用令牌的一种情况下的请求:当我们请求一个时。

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

这里我刚刚添加了EnableCorsAttribute,以便全局启用。

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

上传文件

一切正常;我可以毫无问题地向 Web API 执行 GETPOST 请求,但在尝试上传图像时会出现问题。

要上传到文件,我在一个名为 FileControler 的 ASP.NET MVC 控制器中有一个操作方法。

文件控制器.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);
}

调用 MVC 控制器

这已经是 The FrontEnd 的一部分。

要调用这个方法,我使用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);
    });
}

这是对上述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...
 }); 

问题

如果我从 WebApiConfig.cs 中删除所有 CORS 设置,并且在 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's mode to 'no-cors' to fetch the resource with CORS disabled.

“有趣”的是,如果我尝试使用例如REST Console 调用该网址,我不会得到 404。

我尝试将[HttpOptions] 属性添加到操作方法中;我尝试按照herehere 的描述创建ActionFilterAttributes,甚至在web.config 中设置uip CORS,但无济于事。

我知道问题是 FileController 是一个常规的 MVC 控制器而不是一个 Web API 控制器,但它不应该仍然可以让 CORS 工作吗?

【问题讨论】:

  • 你排序了吗?
  • @sambomartin,不,很遗憾没有。

标签: asp.net-mvc-5 cors asp.net-web-api2 form-data aurelia-fetch-client


【解决方案1】:

你试过了吗

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

在 ApplicationOAuthProvider.cs 文件中

【讨论】:

  • 我刚做了,但没什么区别。我应该在ApplicationOAuthProvider.cs 的哪个位置称呼它?
  • 这里公开覆盖异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
  • 是的,我确实试过了,可惜没用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2018-04-27
  • 2016-06-29
  • 1970-01-01
  • 2014-06-01
相关资源
最近更新 更多