I created a simple ASP.NET web api application. I enabled CORS on it using Microsoft.AspNet.WebApi.Cors
package.
This is how my controller looks:
public class UserController : ApiController
{
[Route("user/name")]
[HttpGet]
public HttpResponseMessage GetUserName()
{
dynamic data = new ExpandoObject();
data.user = HttpContext.Current.User.Identity.Name;
var response = JsonConvert.SerializeObject(data);
var msg = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(response)
};
return msg;
}
}
I am only returning the userid from this controller.
I have hosted the app on IIS 8.5. I have disabled anonymous authentication & enabled windows authentication.
If I use rest client or directly access the endpoint by entering URL in browser, I get the user name. If I use a REST client, I get the response
but if I make AJAX call using jquery, I get 401 status code.
$.ajax({url: 'http://serverName:8899/user/name', method: 'GET' ,
success:function(res){
alert('hello');
}}) ;
The above call works in IE only chrome gives 401 error
How can I fix this error. I am enabling windows authentication using IIS and I have not changed my web.config at all. If this is authentication issue, why I am able to retrieve data when I use rest client?