我编写了一种在Webform asp.net的客户端上载文件的方法,该方法使用resumablejs插件。 另一面,我在mvc项目的控制器上编写了一个方法,并在该项目的webconfig中激活了cors起源,例如:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="*"/>
</customHeaders>
</httpProtocol>
我也喜欢这样:
[EnableCors(origins: "http://localhost:10811", headers: "*", methods: "*")]
public class UploadController : ApiController
{}
但是当我在firefox中调用上载方法时,在控制台中出现此错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5023/Home/UploadFiles. (Reason: CORS request did not succeed)
和Chrome上的此错误:
Response for preflight does not have HTTP ok status.
有一个问题:我用mvc项目的客户端测试了客户端方法,该方法有效。 有什么问题,有人可以帮我吗?
答案 0 :(得分:0)
您将需要一个如下所示的动作过滤器属性:
public class AllowCORSAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
接下来,根据您的要求将此属性应用于您的操作方法或控制器类。我建议在操作级别应用它,因为它不会使所有操作方法都可以跨组织访问:
[AllowCORS]
public ActionResult UploadFile()
答案 1 :(得分:-1)
请遵循以下说明:
<system.webServer>
部分内的ASP.NET MVC项目的web.config中:<httpProtocol>
<customHeaders>
<clear/>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
Application_BeginRequest
方法上的global.asax中,添加一些代码以对飞行情报管理系统进行飞行前响应:if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
"*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"OPTIONS, GET, HEAD, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Accepts, Content-Type, Origin, Authorization, Api-Version, X-API-KEY, USERGUID");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age",
"1200");
HttpContext.Current.Response.End();
}
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
"OPTIONS, GET, HEAD, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
"Accepts, Content-Type, Origin, Authorization, Api-Version, X-API-KEY, USERGUID");
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers",
"Authorization, Api-Version, USERGUID, WWW-Authenticate");