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

zap*_*poo 4 c# http-headers cors asp.net-web-api angularjs

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

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

申请流程如下

1- UI项目从令牌应用程序获取令牌(它需要Windows身份验证.)Ex: awxrsdsaWeffs12da

2- UI应用程序将此标记放入自定义标头,该标头名为"accessToken"

例如:accessToken: awxrsdsaWeffs12da

3- UI应用程序向API Application Ex发送请求: 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);

            ....
}
Run Code Online (Sandbox Code Playgroud)

配置

   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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

所以我正在寻找一个解决方案来调用API应用程序(B)控制器并得到200 :)

问候

Jer*_*eme 13

我通过创建一个响应使用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()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<system.webServer>
    <modules>
      <add name="HandleOptions" type="namespace.OptionsModule" />
    </modules>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

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