Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EnableCors not working in WebApi

I followed the aspnet site tutorial to enable cors and i cant get it working.

Register method on WebApiConfig:

  public static void Register(HttpConfiguration config)
  {
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
        config.MapHttpAttributeRoutes();
   }

Controller:

 public class TestController : Controller
 {
    [Route("test/{*anything}")]
    public ActionResult Index()
    {
        return Json(new { test = "test message" },
            JsonRequestBehavior.AllowGet);
    }
  }

Then i create a simple website with a minimum index.html served by the nodejs live-server making an ajax request and it works ok when debuggin locally. But when i publish it to azure i get the following error :

XMLHttpRequest cannot load http://mysite.azurewebsites.net . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access

EDIT: I have installed the Microsoft.AspNet.WebApi.Cors version 5.2.3

like image 802
gog Avatar asked Sep 11 '26 08:09

gog


1 Answers

Seems like you are using MVC Controller instead of Api Controller (unless its DotNet Core). Change the Base class to ApiController with action return type IHttpResponseMessage and return Ok (new { test = "test message" });

like image 115
Developer Avatar answered Sep 12 '26 20:09

Developer