Copied to clipboard

Flag this post as spam?

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


  • Darren Eccles 59 posts 298 karma points
    Apr 21, 2016 @ 14:31
    Darren Eccles
    0

    How do I get around the cross domain problem using the umbraco Web API using POST

    Hi Guys, really struggling on this one. Has anyone managed to get around the cross domain problem using the post method on the UmbracoApiController.

    I feel I've exhausted all efforts to try and find a solution, I even set up a new web api solution with in my umbraco project. I managed to get the cross domain problem solved in the web api solution however when I reference the umbraco solution into the web api solution I have conflicting issues. When I fixed one error, it led to another error and so on.

    It just really frustrating that I have a umbraco solution and all my api methods written accessing the form, content and media services, and it works fantastic. I've even written the jquery code to post and get the data (within the same domain) and it works.

    The problem just occurs when I try to post from a different URL (cross domain problem (aka CORS)).

    I know I've rambled on, but I've spent nearly two days looking at this problem and the only solution I can see is avoid POST methods.

    Any help on this would be really appreciated.

    Sorry for going on, Darren

  • Casper 70 posts 308 karma points
    Apr 21, 2016 @ 15:49
    Casper
    0

    It sounds like you need to add a response header that allow cross domain access to the resource:

    Access-Control-Allow-Origin: *
    

    or

    Access-Control-Allow-Origin: http://www.yourdomain.com/
    

    If you want to set it up globally this can be done in application.config or web.config:

    <configuration>
       <system.webServer>
          <httpProtocol>
             <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
             </customHeaders>
          </httpProtocol>
       </system.webServer>
    </configuration>
    

    Else you can add it from within the method that you need to allow cross domain access to.

  • Darren Eccles 59 posts 298 karma points
    Apr 21, 2016 @ 19:18
    Darren Eccles
    0

    Hi Casper,

    I've already added the following into my web.config file and its made no difference:

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET,POST" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
        <remove name="X-Powered-By" />
      </customHeaders>
    </httpProtocol>
    

    I some how have to install and enable CORS on my umbraco 7 solution

    Darren

  • Bo Damgaard Mortensen 719 posts 1207 karma points
    Apr 21, 2016 @ 20:53
    Bo Damgaard Mortensen
    0

    Hi Darren,

    Can you share the javascript code snippet, that you're using to make the POST? :-)

    Thanks!

  • Darren Eccles 59 posts 298 karma points
    Apr 21, 2016 @ 21:16
    Darren Eccles
    0

    Hi, I'm building an web app using Ionic which uses Angularjs:

        var url = "http://localhost:52992/umbraco/api/umbracoapicontroller/postmethod";
        var data = JSON.stringify({
            forename: "John",
            surname: "Smith"
        });
        $http.post(url, data)
            .success(function (data, status, headers, config) {
                console.log('Success', data);
            })
            .error(function (data, status, headers, config) {
                console.error('Error', data);
            });
    

    Also, this is the Get method I'm using and this works:

    var url = "http://localhost:52992/umbraco/api/UmbracoApiController/GetMethod?id=1";
        $http.get(url)
            .then(function (data) {
                console.log('Success', data);
            }, function (data) {
                console.error('ERR', data);
            })
    

    Thanks

  • Hywel Rees 56 posts 224 karma points
    Apr 21, 2016 @ 22:02
    Hywel Rees
    0

    Hi Darren,

    To get around this issue, I normally install the Microsoft.AspNet.WebApi.Cors NuGet package.

    Once installed, you will need to configure it in your App_Start\WebApiConfig.cs with the line

    config.EnableCors();
    

    Once complete, all that remains is to mark your API controller classes with the following attribute

        [EnableCors("*", "*", "*")]
    

    This will allow all methods in the controller and all HTTP verbs. You can replace the wildcards with specific details if desired, and you can also apply this attribute at the method level instead of class level.

    Hope this helps.

    Cheers,

    Hywel

  • Darren Eccles 59 posts 298 karma points
    Apr 21, 2016 @ 22:12
    Darren Eccles
    0

    Hi Hywel,

    Thanks, but if I was running a standard .net web api 2 solution, this wouldn't be a problem, the instructions above that you give will work f ine.

    However within my umbraco 7 solution, I have no App_start folder or WebApiConfig.cs file.

    I've also tried installing CORS into my umbraco solution and it updated my web.config file which cause the solution to fail.

    I know what the problem is (cross domain aka CORS), but I just don't know how to fix it within my umbraco solution using the UmbracoApiController.

    Thanks again

    Darren

  • Casper 70 posts 308 karma points
    Apr 21, 2016 @ 22:22
  • Casper 70 posts 308 karma points
    Apr 22, 2016 @ 07:25
    Casper
    1

    Hi Darren,

    Did you try out the approach in the link? I got it to work:

    1. PM > Install-Package Microsoft.AspNet.Cors -Version 5.2.3
    2. Create App_Start\WebApiConfig.cs and add:

      using System.Web.Http;
      using System.Web.Http.Cors;
      
      
      namespace Website
      {
          public static class WebApiConfig
          {
              public static void Register(HttpConfiguration config)
              {  
                  var corsAttr = new EnableCorsAttribute("*", "*", "*");
                  config.EnableCors(corsAttr);
              }
          }
      }
      
    3. Add a class that inherit from UmbracoApplication and override OnApplicationStarting and register your WebApiConfig:

      using System;
      using System.Web.Http;
      using Umbraco.Web;
      
      
      namespace Website.EventHandlers
      {
          public class WebApplication : UmbracoApplication
          {
              protected override void OnApplicationStarting(object sender, EventArgs e)
              {
                  base.OnApplicationStarting(sender, e);
                  GlobalConfiguration.Configure(WebApiConfig.Register);
              }
          }
      }
      
    4. Change Global.asax so it inherits from the class we just created:

      <%@ Application Inherits="Website.EventHandlers.WebApplication" Language="C#" %>
      

    This works for me :)

  • Andreas Bösig Vestergaard 4 posts 84 karma points
    Oct 03, 2017 @ 10:58
    Andreas Bösig Vestergaard
    0

    What Global.asax is that? Mine doesn't look like that at all.

  • Casper 70 posts 308 karma points
    Oct 03, 2017 @ 11:13
    Casper
    0

    Hi Andreas,

    What does yours look like?

    Out of the box it should just contain this:

    <%@ Application Inherits="Umbraco.Web.UmbracoApplication" Language="C#" %>

  • Andreas Bösig Vestergaard 4 posts 84 karma points
    Oct 03, 2017 @ 11:15
    Andreas Bösig Vestergaard
    0

    Dammit, i was looking in the wrong place...Sorry to disturb ;)

  • Casper 70 posts 308 karma points
    Oct 03, 2017 @ 11:17
    Casper
    1

    No problem :)

  • Darren Eccles 59 posts 298 karma points
    Apr 22, 2016 @ 08:22
    Darren Eccles
    0

    Hi Casper,

    I just tried following you instructions, but after installing 'Microsoft.AspNet.Cors.5.2.3' through NuGet, I can't access 'System.Web.Http.Cors' only 'System.Web.Cors'

    Have I installed the wrong package?

    Thanks

    Darren

  • Darren Eccles 59 posts 298 karma points
    Apr 22, 2016 @ 09:21
    Darren Eccles
    0

    Hi Casper,

    I got it working, I can't thank you enough, your a super star :) :).

    I had to install 'Microsoft.AspNet.WebApi.Cors'

    The funny thing is, yesterday I'd already installed this package and it caused my solution to break due to the changes in the web.config.

    So, this is what worked for me, I installed 'Microsoft.AspNet.Cors' 5.2.3 first, this didn't work, I uninstalled it and installed 'Microsoft.AspNet.WebApi.Cors' 5.2.3 and it worked, then followed the instructions from Casper above.

    Also remember to remove any reference to cross origin stuff in the web.config file (e.g. add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" )

    Once again, thank you so much to everyone. Now I can crack on with my project.

    Darren

  • Casper 70 posts 308 karma points
    Apr 22, 2016 @ 13:39
    Casper
    0

    I was a bit to fast, it was the Microsoft.Aspnet.WebApi.Cors i installed. Glad you got i up and running :)

  • Nadine Fisch 159 posts 429 karma points
    Jun 08, 2018 @ 09:18
    Nadine Fisch
    0

    I made the same adjustments but I get following error:

    The type Website.EventHandlers.WebApplication could not be found. Any help?

  • Nadine Fisch 159 posts 429 karma points
    Jun 08, 2018 @ 09:51
    Nadine Fisch
    0

    I moved the classes to the folder APP_Code

  • Jordan Lane 28 posts 130 karma points c-trib
    May 24, 2019 @ 05:25
    Jordan Lane
    3

    If anyone is looking to get this working in v8, I found an easy solution using the new application composers:

    • Step 1: Install the Microsoft Cors Package.
    • Step 2: Create a composer somewhere in your project, I opted to create a Composers directory.
    • Step 3: Add the following

      using System.Web.Http;
      using System.Web.Http.Cors;
      using Umbraco.Core;
      using Umbraco.Core.Composing;
      
      
      namespace Your.Web.Composers
      {
      [RuntimeLevel(MinLevel = RuntimeLevel.Boot)]
      public class CorsComposer : IUserComposer
      {
          public void Compose(Composition composition)
          {
              GlobalConfiguration.Configure(Register);
          }
      
      
      
      public static void Register(HttpConfiguration config)
      {
          var corsAttr = new EnableCorsAttribute("*", "*", "*");
          config.EnableCors(corsAttr);
      }
      
      } }

    Hope that helps!

  • matthew mcalister 12 posts 84 karma points
    Jul 29, 2020 @ 15:38
    matthew mcalister
    0

    Has this worked for anyone else? I've just attempted this in 8.1.3 and I receive CORS preflight failures.

    ....from origin 'http://umbcore.local' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

  • Nastassia 2 posts 72 karma points
    Nov 19, 2019 @ 09:33
    Nastassia
    0

    Or you can go without create Composer and enable CORS on WebApiConfig registration.

    • Install Microsoft.AspNet.Cors package
    • enable CORS in your WebApiConfig before register routs (it is urgent)

      public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(new EnableCorsAttribute("{allowed origins}", "", ""));

          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
      }
      

      }

    • add headers to web.config customHeaders section

      <remove name="Access-Control-Allow-Origin" />

      <add name="Access-Control-Allow-Origin" value="{allowed origin}" />

      <remove name="Access-Control-Allow-Credentials" />

      <add name="Access-Control-Allow-Credentials" value="true" />

  • Abanoub Ayaad 9 posts 79 karma points
    May 19, 2021 @ 19:50
    Abanoub Ayaad
    0

    Thanks for sharing but not working

  • danielibanez 8 posts 76 karma points
    Jul 20, 2021 @ 19:15
    danielibanez
    0

    I ended up managing CORS via Azure.

Please Sign in or register to post replies

Write your reply to:

Draft