0

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?

SharpCoder
  • 18,279
  • 43
  • 153
  • 249
  • Possible duplicate of [How can I pass windows authentication to webservice using jQuery?](http://stackoverflow.com/questions/1002179/how-can-i-pass-windows-authentication-to-webservice-using-jquery) – Erik Philips Apr 10 '17 at 20:22

1 Answers1

0

Make sure you also register CORS support either Globally, at the Controller, or at the Action.

Global - In your WebApiConfig.cs file from App_Start folder add:

public static void Register(HttpConfiguration config) {

// New code: var cors = new EnableCorsAttribute( origins: "*", headers: "*", methods: "*"); config.EnableCors(cors);

// Other configurations

}

Controller or Action - If desired/required to place support at these levels (this will overwrite global settings - Action > Controller > Config). Above Controller or Action signature:

[EnableCors(origins: "http://localhost:[port #]", headers: "*", methods: "*")]

Note: * are "wildcards", might want to put the domain making the request ex:(http://localhost:[port #])

Something that is very easy to miss/forget...

IN solution explorer, right-click api-project. In properties window set 'Anonymous Authentication' to Enabled !!!

Wes
  • 11
  • 2