Copied to clipboard

Flag this post as spam?

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


  • Fredrik Heidgert 9 posts 29 karma points
    Apr 07, 2015 @ 18:22
    Fredrik Heidgert
    0

    Web API 2 and cross-origin resource sharing (CORS)

    Hi!

    I'm developing an app for iOS and Android which uses Umbraco as a backend.

    I have successfully upgraded my site to MVC 5 and Web API 2 to be able to support CORS correctly (using the Microsoft.AspNet.WebApi.Cors NuGet package).

    All is fine and dandy when calling my API methods by hand (using Fiddler) but when calling them from my app it seems like the CORS calls aren't correctly handled.

    I am enabling Cors during application start like below:

    My Global.asax.cs:

    public class MvcApplication : Umbraco.Web.UmbracoApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
    

    My WebApiConfig class:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();
        }
    }
    

    I am also decorating my api-methods with the Cors-attribute like this:

    [EnableCors("*", "*", "*")]
    public class AuthController : UmbracoApiController
    {
        [HttpGet]
        public HttpResponseMessage Login(string email, string password)
        {
            //code removed for brevity
        }
    }
    

    As my app is calling the Login-method it will send a preflight-request - http method OPTIONS (how and why is in detail explained here:

    http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works

    I always get a 404 not found when doing this. I should receive a 200 which would let my app continue with the actual api request.

    Anyone with experience with Web API, CORS and Umbraco who could help a poor guy out?

    Thanks in advance :)

    /Fredrik Heidgert

  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 07, 2015 @ 22:06
    Biagio Paruolo
    1

    404 is caused by a routing problem, not CORS.

    I think that there is a fight between WebAPI and Umbraco application.

     

  • Fredrik Heidgert 9 posts 29 karma points
    Apr 07, 2015 @ 22:11
    Fredrik Heidgert
    0

    You may be right in this, but since this call works (the api method is being called):

    GET http://myapi.local/umbraco/api/auth/login?username=name&password=pass
    

    shouldn't this also work then, if CORS is configured correctly?

    OPTIONS http://myapi.local/umbraco/api/auth/login
    

    There are of course some differences in the headers.

  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 08, 2015 @ 00:06
    Biagio Paruolo
    0

    Uhm... I'll check into a code that I build with CORS and write here my config.

  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 08, 2015 @ 09:45
    Biagio Paruolo
    0

    Hi,

    into web.config under   <system.webServer>, I've:

    <handlers>
          <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
          <remove name="OPTIONSVerbHandler" />
          <remove name="TRACEVerbHandler" />
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
    In WebApiConfig.cs
    public static void Register(HttpConfiguration config)
            {
    
                // Web API configuration and services
                config.EnableCors();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
    So I can use:
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    
  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 08, 2015 @ 09:47
    Biagio Paruolo
    0

    I think that is better to have two projects: one for Umbraco and one for WebApi...

  • Fredrik Heidgert 9 posts 29 karma points
    Apr 08, 2015 @ 10:30
    Fredrik Heidgert
    0

    When you say two projects, do you still run them under the same web application?

    I noticed that you add a route config yourself. Don't you use the /umbraco/api/... routes?

  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 08, 2015 @ 10:51
    Biagio Paruolo
    0

    No, I think it's no possibile under same web application...but two application where webAPI use umbraco DLL as reference.

    You see that route because I used external webAPI. 

    I'll try me too.

     


  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 08, 2015 @ 10:59
  • Biagio Paruolo 1500 posts 1641 karma points c-trib
    Apr 08, 2015 @ 16:29
    Biagio Paruolo
    0

    Read here. I think that you can have some helps:

    http://24days.in/umbraco/2014/angular-powered-frontend/

     

  • Fredrik Heidgert 9 posts 29 karma points
    Apr 10, 2015 @ 13:48
    Fredrik Heidgert
    0

    Biagio,

    Thanks for all your help. I have looked at the links you sent but they didn't really provide any solution for the problem at hand.

    The first one (https://our.umbraco.org/forum/umbraco-7/using-umbraco-7/61109-Issue-with-CORS-when-posting-to-web-api) seemed to have worked around the problem by having the Web API running under the same application, which I can't use since the calls come from apps.

    The second one (http://24days.in/umbraco/2014/angular-powered-frontend/) says nothing of CORS I'm afraid.

    I have verified my web.config and it looks just like yours. The WebApiConfig.cs also looks like yours except the route configs which I also cannot use since I need to inherit from the UmbracoApiController class.

    The problem is still that GET and POST requests works as it should but a pre-flight OPTIONS call to the exact same method gives a 404.

  • Alessandro Bellisai 30 posts 120 karma points
    Aug 07, 2015 @ 08:51
    Alessandro Bellisai
    106

    Hi Fredrik

    I found the solution for the 405 error OPTIONS Method not allowed!

    After update umbraco to MV5 and WebAPI2, you have to install the CORS package.

    After updatre correctly umbraco, the key point is to change the Global.asax editing the correct name of Inherits attribute with correct name of the class:

    <%@ Application Codebehind="Global.asax.cs" Inherits="MyApplication" Language="C#" %>
    

    Then on MyApplication.cs you have to override OnApplicationStarting method:

    public class MyApplication: Umbraco.Web.UmbracoApplication
    {
        protected override void OnApplicationStarting(object sender, EventArgs e)
        {
            base.OnApplicationStarting(sender, e);
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
    }
    

    Then, as correctly reported on previous post, on WebApiConfig.cs you have to enable cors:

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var corsAttr = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(corsAttr);
        }
    }
    

    As final step i've remove from web.config the Access-Control-Allow-Origin:

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

    Bye

  • Juan 2 posts 72 karma points
    Aug 10, 2016 @ 16:21
    Juan
    0

    Thanks Alessandro your solution works great you saved my day.

Please Sign in or register to post replies

Write your reply to:

Draft