1,ASP.NetMVC(.NetFramework)的MVC和WebApi对于允许跨域的设置方式是不一样的。这里说明的是.NetMVC的跨域方式。
首先,安装 CORS 库。在包管理器控制台中运行以下命令:
Install-Package Microsoft.AspNet.WebApi.Cors
2,在你的 Global.asax.cs
文件中的 Application_BeginRequest()
方法中添加以下代码:
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
在这段代码中,我们允许任何源("*")发起跨域请求,并且允许 "GET" 和 "POST" 这两种请求方法,同时允许 "Content-Type" 和 "Accept" 这两种请求头。如果你有特定的源、请求方法或请求头需要允许,可以修改这些参数。
这种方法是全局启用 CORS,会影响到你的所有控制器和操作。如果你想要对特定的控制器或操作启用 CORS,可能需要使用其他方法。
安全提醒:在生产环境中使用 CORS 时,请确保只允许可信的源进行跨域请求,避免潜在的安全风险。
要在 AJAX POST 请求中携带 cookie,您需要在 AJAX 请求中设置 withCredentials
属性为 true
。以下是一个使用 jQuery 发起 AJAX POST 请求的示例:
$.ajax({
type: 'POST',
url: 'http://example.com',
data: { key: 'value' },
xhrFields: {
withCredentials: true
},
beforeSend: function(xhr) {
xhr.setRequestHeader("My-Header", "My-Header-Value");
},
success: function(response) {
// 处理响应...
},
error: function(xhr, status, error) {
// 处理错误...
}
});
在这段代码中,xhrFields: { withCredentials: true }
就是设置 AJAX 请求带上 cookie 的部分。
另外,服务器端也需要设置正确的 CORS 头部来接受带有 cookie 的请求。在之前的例子中,我们在 Global.asax.cs
文件中的 Application_BeginRequest()
方法设置了 CORS 头部,我们需要再添加一行代码来接受带有 cookie 的请求:
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://origin.com");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, My-Header");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
在这段代码中,我们添加了 Access-Control-Allow-Credentials: true
头部来接受带有 cookie 的请求。还需要注意的一点是,当 Access-Control-Allow-Credentials
设置为 true
时,Access-Control-Allow-Origin
头部不能设置为 "*"
,必须明确指定具体的源(在这个例子中是 "http://origin.com"
)。
最后,请注意这些操作可能会增加安全风险,因为你的应用可能会接受到带有用户会话信息的请求。在配置 CORS 和处理 cookie 时,一定要确保你了解这些操作的安全影响。