简体   繁体   中英

401 Unauthorized error when making ajax call to asp.net web api endpoint with window authentication enabled

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?

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 !!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM