gpt4 book ai didi

c# - 在 Asp.net Web API 中处理 CORS 预检

转载 作者:太空狗 更新时间:2023-10-30 00:01:22 26 4
gpt4 key购买 nike

我的架构中有三个应用程序。
它们在同一台服务器上,但具有不同的端口号。

A - Token Application (port 4444) - Asp.net WebApi
B - API Application (port 3333) - Asp.net WebApi
C - UI Application (port 2222) - AngularJS App.

申请流程如下

1- UI 项目从 token 应用程序获取 token (它需要 Windows 身份验证。)例如:awxrsdsaWeffs12da

2- UI 应用程序将此 token 放入名为“accessToken”的自定义 header

例如:访问 token :awxrsdsaWeffs12da

3- UI 应用程序向 API 应用程序发送请求例如:http:myaddress:3333/api/TheRestServiceHere

UI 应用程序出现 401 错误。其中发送 OPTIONS 方法。 (我猜是预检问题)

在我的 web api 项目中,我启用了如下所示的 Cors。

public static void Register(HttpConfiguration config)
{
....

//CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

....
}

配置

   public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{

//CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors();


// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);


var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
json.SerializerSettings.Formatting = Formatting.None;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}

所以我正在寻找调用 API 应用程序 (B) Controller 的解决方案并获得 200 :)

问候

最佳答案

我通过创建一个响应使用 OPTIONS 动词的请求的模块在我正在处理的应用程序中解决了这个问题。您可能应该稍微修改它以包括应用程序请求的动词和内容类型。就我而言,我决定将所有内容都发布为 JSON(这需要进行飞行前检查)。模块如下:

public class OptionsModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += (sender, args) =>
{
var app = (HttpApplication) sender;

if (app.Request.HttpMethod == "OPTIONS")
{
app.Response.StatusCode = 200;
app.Response.AddHeader("Access-Control-Allow-Headers", "content-type");
app.Response.AddHeader("Access-Control-Allow-Origin", APISettings.ApplicationOrigin);
app.Response.AddHeader("Access-Control-Allow-Credentials", "true");
app.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
app.Response.AddHeader("Content-Type", "application/json");
app.Response.End();
}
};
}

public void Dispose()
{
}
}

然后你需要在你的 web.config 中注册它:

<system.webServer>
<modules>
<add name="HandleOptions" type="namespace.OptionsModule" />
</modules>
</system.webServer>

您可能想要做的另一件事是明确指定允许的来源。 Chrome 不喜欢那里有通配符。

关于c# - 在 Asp.net Web API 中处理 CORS 预检,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31290317/

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