Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • JohanO 2 posts 22 karma points
    Feb 21, 2020 @ 09:15
    JohanO
    0

    CORS problem with API. HTTP OPTIONS call returns 405

    Hi,

    I have added a WebAPI to my Umbraco 8 site, by subclassing UmbracoApiController. Calling the WebAPI using Postman works fine, but when calling it from an external web app it fails. I am getting problems with CORS in the browser. It says OPTIONS {myendpoint} 405 (Method Not Allowed) and Access to {myendpoint} has been blocked by CORS policy: Response to preflight request doesn't pass access control check

    I have modified the web.config file to add the headers required by CORS ('Access-Control-Allow-Origin' and 'Access-Control-Request-Headers') and verified with Postman they are correct. In short:

    • HTTP POST {mysite}/umbraco/api/{mystuff} works fine and has correct CORS headers.
    • HTTP OPTIONS {mysite}/umbraco/api/{mystuff} fails with 405.

    Found this code snippet on how to add CORS, but that code is for Umbraco 7 and doesn't even compile for Umbraco 8.

    Any ideas?

  • JohanO 2 posts 22 karma points
    Feb 22, 2020 @ 11:16
    JohanO
    0

    Solved the problem!

    Had to do two things.

    1. Add CORS headers to return in web.config
    2. Add [HttpOptions] header to my controller action.

    web.config

    <configuration>
      ...
      <system.webserver>
        ...
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
            <add name="Access-Control-Max-Age" value="86400" />
          </customHeaders>
        </httpProtocol>
    

    MyController.cs

    public class MyController : UmbracoApiController
    {
        [HttpPost]
        [HttpOptions]
        public Task<IHttpActionResult> MyMethod()
        {
            ...
        }
    }
    
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies