asp.net-mvc-5 – Web API和MVC 5控制器上的CORS:使用fetch和FormData上传图像

我有一个应用程序,其前端和后端在不同的.NET项目上运行.
前端是在ASP.NET 5上运行的 Aurelia Web应用程序.这个Aurelia应用程序(从现在开始在FrontEnd上)从Web API 2 / MVC 5应用程序(以下称为BackEnd)获取所有数据.

由于FrontEnd和BackEnd是不同的应用程序,因此我使用CORS设置,包括Web API和用于令牌承载请求的Start.Auth.cs.

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

现在,对于一些代码(这都在BackEnd中)

Start.Auth.cs

整个应用程序都驻留在一个登录表单后面,所以在Start.Auth.cs文件中,除了在静态Startup()上设置基于令牌的身份验证之外,我还有一些中间件可以添加Access -Control-Allow-Origin标头在一个没有令牌可用的情况下的请求:当我们请求一个令牌时.

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执行GET和POST请求,尝试上传图像时会出现问题.

上传文件,我在ASP.NET MVC控制器中有一个名为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);
}

调用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);
    });
}

这是对上面上传方法调用

// 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.

“有趣”的是,如果我尝试调用该URL,对于intance,REST Console我没有得到404.

我已经尝试将[HttpOptions]属性添加到action方法中;我已经尝试过创建ActionFilterattributes,如herehere所述,甚至在web.config中设置uip CORS,但无济于事.

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

解决方法

你试过这个吗?

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

在ApplicationOAuthProvider.cs文件

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....