Enable OPTIONS header for CORS on .NET Core Web API

后端 未结 7 1535
温柔的废话
温柔的废话 2020-11-28 06:55

I solved this problem after not finding the solution on Stackoverflow, so I am sharing my problem here and the solution in an answer.

After enabling a cross domain p

7条回答
  •  有刺的猬
    2020-11-28 07:28

    I wanted to allow this for a single method, not using a middleware to allow this on any method. This is what I ended doing:

    Manual handling of the 'OPTIONS' method

    [HttpOptions("/find")]
    public IActionResult FindOptions()
    {
        Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)Request.Headers["Origin"] });
        Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
        Response.Headers.Add("Access-Control-Allow-Methods", new[] { "POST, OPTIONS" }); // new[] { "GET, POST, PUT, DELETE, OPTIONS" }
        Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
        return NoContent();
    }
    

    [HttpPost("/find")]
    public async Task FindOptions([FromForm]Find_POSTModel model)
    {
        AllowCrossOrigin();
        
        // your code...
    }
    
    private void AllowCrossOrigin()
    {
        Uri origin = null;
        Uri.TryCreate(Request.Headers["Origin"].FirstOrDefault(), UriKind.Absolute, out origin);
    
        if (origin != null && IsOriginAllowed(origin))
            Response.Headers.Add("Access-Control-Allow-Origin", $"{origin.Scheme}://{origin.Host}");
    }
    

    And of course, you can implement IsOriginAllowed as you wish

    private bool IsOriginAllowed(Uri origin)
    {
        const string myDomain = "mydomain.com";
        const string[] allowedDomains = new []{ "example.com", "sub.example.com" };
    
        return 
               allowedDomains.Contains(origin.Host) 
               || origin.Host.EndsWith($".{myDomain}");
    }
    
    

    You can find more details on how to enable CORS for POST requests on a single endpoint

提交回复
热议问题