我写了一个在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中调用upload方法时,我在控制台中出现了这个错误:
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项目的一个客户端测试了客户端方法,它是有效的。有什么问题吗,有人能帮我吗?
发布于 2018-09-30 01:25:01
您将需要一个操作过滤器属性,如下所示:
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()发布于 2020-02-21 00:48:21
请按照以下说明操作:
<system.webServer>部分中:<httpProtocol>
<customHeaders>
<clear/>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>Application_BeginRequest方法为CORS添加一些印前检查响应代码: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");https://stackoverflow.com/questions/52569523
复制相似问题