我在处理COR时遇到了一些奇怪的问题。 首先,我使用url:https://local-xyz.mydomain.com托管应用程序,并从https://local.mydomain.com调用它
对于“ GET”请求,它工作正常,但对于“ POST”,则给出错误错误。 有多种情况:
如果我在标头中传递Content-Type,则会出现以下错误:
Access to XMLHttpRequest at 'https://local-xyz.mydomain.com/actionmethod' from origin 'https://local.mydomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
如果我删除内容类型,则它在我的模型中正常工作bur属性未绑定。表示所有属性均为空
如果我尝试刷新如下所示的选项请求:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
Application_BeginRequest没有收到POST请求的调用。
我的操作方法过滤器是:
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (filterContext.HttpContext.Response != null && filterContext.HttpContext.Request != null &&
filterContext.HttpContext.Request.UrlReferrer != null)
{
var requestHost = filterContext.HttpContext.Request.UrlReferrer.GetLeftPart(UriPartial.Authority);
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", requestHost);
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
filterContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
base.OnActionExecuted(filterContext);
}
}
我调用操作方法的方式是:
fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(resp => {
if (resp.ok) return resp.json()
})
.then(resp => resp);
如果我缺少任何步骤,请提出建议。
谢谢, 桑比尔