ServiceStack - 两次添加CORS模块?

时间:2017-08-08 19:04:45

标签: cors servicestack

加载ServiceStack Api项目时出现异常。这是ServiceStack输出:

"startUpErrors": [{
    "errorCode": "ArgumentException",
    "message": "An item with the same key has already been added.",
    "stackTrace": "[Object: 8/8/2017 6:47:38 PM]:\n[REQUEST: ]\n
    System.ArgumentException: An item with the same key has already been added.\r\n   
    at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)\r\n   
    at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)\r\n   
    at ServiceStack.CorsFeature.Register(IAppHost appHost)\r\n   
    at ServiceStack.ServiceStackHost.LoadPluginsInternal(IPlugin[] plugins)",
    "errors": []
}],

这是我的AppHost.cs文件中的配置方法:

   public override void Configure(Container container)
    {
        var allowedOrigin = CloudConfigurationManager.GetSetting("CORS.AllowedOrigin");

        Plugins.Add(new CorsFeature(allowedOrigins: allowedOrigin, allowedHeaders: "Content-Type,Authorization"));
        Plugins.Add(new ValidationFeature());

        ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
        SetConfig(new HostConfig
        {
            DefaultContentType = MimeTypes.Json,
            EnableFeatures = Feature.All.Remove(Feature.Html),
            GlobalResponseHeaders =
            {
                { "Access-Control-Allow-Origin", allowedOrigin },
                { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH" },
                { "Access-Control-Allow-Headers", "Content-Type,Authorization" },
            }
        });

        var connectionString = ConfigurationManager.ConnectionStrings["BareCove.ConnectionString"].ConnectionString;
        var dbFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);

        container.Register<IDbConnectionFactory>(c => new MultiTenantDbFactory(dbFactory));

        PreRequestFilters.Add((req, res) => {
            // Handles Request and closes Response after emitting global HTTP Headers
            if (req.Verb == "OPTIONS")
            {
                res.StatusCode = 200;
                res.EndRequest();
            }
        });

        GlobalRequestFilters.Add((req, res, dto) =>
        {

        });

        ServiceExceptionHandlers.Add((req, request, exception) => 
        {
            // Log
            //
            _exceptionLogger?.Invoke($"Service exception caught in AppHost.cs.", new[] { exception });

            // Continue with default error handling
            //
            return null;

            // Or return your own custom response
            // return DtoUtils.CreateErrorResponse(request, exception);
        });

        // Handle unhandled exceptions outside of services
        //
        UncaughtExceptionHandlers.Add((req, res, operationName, exception) => 
        {
            // Log. TODO: incorporation operationName into message
            //
            _exceptionLogger?.Invoke($"Unhandled exception caught in AppHost.cs. Operation: {operationName}.", new[] { exception });

            res.Write("Error: {0}: {1}".Fmt(exception.GetType().Name, exception.Message));
            res.EndRequest(skipHeaders: true);
        });

        ConfigureAuth(new Lazy<IDbConnectionFactory>(() => new MultiTenantDbFactory(dbFactory)));
    }

所以不知怎的,我不止一次注册CORS插件。或者其他一些模块正在加载CORS插件。

使用此异常,应用程序运行正常。我只是无法在调试时捕获它并找出它被设置多次的位置。

感谢您的任何见解。

1 个答案:

答案 0 :(得分:0)

删除GlobalResponseHeadersPreRequestFilters,它们已经由CorsFeature插件添加。