I'm developing a website using ASP.NET MVC5 and WEB API 2.2. In my web api controller, I have an if condition to check if user is logged in:
if (!User.Identity.IsAuthenticated)
{
return BadRequest("NotLoggedIn");
}
This works fine for if there's no "www" in front of my domain name. But it will return BadRequest("NotLoggedIn")
if "www" Is added to my domain name. For example, my domain is example.com. If user type www.example.com, the webpage will make an AJAX request to example.com/api/controller, and User.Identity.IsAuthenticated will return false. It will return ture if user just enter example.com.
I have enabled CORS in the global level:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("http://www.example.com", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Anyone knows how to solve this problem?
I have solved this problem.
I need to decorate the api controller with:
[EnableCorsAttribute("http://www.example.com" , "*", "*", SupportsCredentials = true)]