gpt4 book ai didi

asp.net-mvc - 处理对 ASP.NET MVC 操作的 CORS 预检请求

转载 作者:行者123 更新时间:2023-12-02 12:26:26 33 4
gpt4 key购买 nike

我正在尝试对 ASP.NET MVC Controller 操作执行跨域 POST 请求。该 Controller 操作接受并使用各种参数。问题是,当预检请求发生时, Controller 操作实际上尝试执行,因为 OPTIONS 请求没有传递任何数据, Controller 操作会抛出 500 HTTP 错误。如果我删除使用该参数的代码或参数本身,则整个请求链将成功完成。

如何实现的示例:

Controller 操作

public ActionResult GetData(string data)
{
return new JsonResult
{
Data = data.ToUpper(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

客户端代码

<script type="text/javascript">
$(function () {
$("#button-request").click(function () {
var ajaxConfig = {
dataType: "json",
url: "http://localhost:8100/host/getdata",
contentType: 'application/json',
data: JSON.stringify({ data: "A string of data" }),
type: "POST",
success: function (result) {
alert(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: Status: ' + textStatus + ', Message: ' + errorThrown);
}
};

$.ajax(ajaxConfig);
});
});
</script>

现在,每当预检请求发生时,它都会返回 500 HTTP 代码,因为“data”参数为 null,因为 OPTIONS 请求没有传递任何值。

服务器应用程序已在我的本地 IIS 中的端口 8100 上设置,运行客户端代码的页面设置在端口 8200 上以模拟跨域调用。

我还使用以下 header 配置了主机(在 8100 上):

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, GET
Access-Control-Allow-Origin: http://localhost:8200

我发现的一个解决方法是检查执行操作的 HTTP 方法,以及是否是仅返回空白内容的 OPTIONS 请求,否则执行操作代码。就像这样:

public ActionResult GetData(string data)
{
if (Request.HttpMethod == "OPTIONS") {
return new ContentResult();
} else {
return new JsonResult
{
Data = data.ToUpper(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}

但这种方法对我来说感觉非常笨拙。我考虑过将这种逻辑添加到 Attribute 中,但即使这也意味着装饰将使用 CORS 调用的每个操作。

是否有更优雅的解决方案来让此功能发挥作用?

最佳答案

所以我找到了一个有效的解决方案。对于每个请求,我都会检查它是否是 CORS 请求以及该请求是否带有 OPTIONS 动词,表明它是预检请求。如果是,我只是发回一个空响应(当然,它只包含 IIS 中配置的 header ),从而否定 Controller 操作执行。

然后,如果客户端确认允许根据预检返回的 header 执行请求,则会执行实际的 POST 并执行 Controller 操作。我的代码示例:

protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin", StringComparer.OrdinalIgnoreCase) &&
Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
}

如上所述,这对我有用,但如果有人知道更好的方法,或者我当前实现中的任何缺陷,我将不胜感激。

关于asp.net-mvc - 处理对 ASP.NET MVC 操作的 CORS 预检请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13624386/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com