How to solve ASP.NET Web API CORS Preflight issue when using PUT and DELETE requests with multiple origins?

前端 未结 2 1684
离开以前
离开以前 2021-02-07 19:15

I have an ASP.NET web API that is being called by three different SPA. I am using windows authentication for the web API. I initially tried to configure CORS in the Web.config l

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 19:36

    Create custom attribute using ICorsPolicyProvider something like following to check if the requested origin is allowed or not

        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = false)]
        public class EnableCorsForAPIKeysAttribute :
          Attribute, ICorsPolicyProvider, IFilter
        {
            public async Task GetCorsPolicyAsync(
              HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var corsRequestContext = request.GetCorsRequestContext();
                var originRequested = corsRequestContext.Origin;
                if (await IsValidOrigin(originRequested)) //Check if requested origin is valid or not
                {
                    // Grant CORS request
                    var policy = new CorsPolicy
                    {
                        AllowAnyHeader = true,
                        AllowAnyMethod = true
                    };
                    policy.Origins.Add(originRequested);
                    return policy;
                }
                else
                {
                    // Reject CORS request
                    return null;
                }
            }
    
            public bool AllowMultiple { get {return false;} }
        }
    

    To use it, add it to your API controller

    [EnableCorsForAPIKeys]
    public class APIBaseController : ApiController
    {
    }
    

提交回复
热议问题