简体   繁体   中英

ASP.NET MVC 4 - 401 Access Denied

I've created a very simple WebAPI with one get command that just returns an integer. It works perfectly fine when I run it in a browser. But when I try to access problematically from another project in the solution I get the following:

2013-05-15 17:46:47,811 - Response: StatusCode: 401, ReasonPhrase: 'Access Denied',Version: 1.1, Content: System.Net.Http.StreamContent, Headers:

{

Date: Wed, 15 May 2013 16:46:47 GMT

Server: Microsoft-IIS/5.1

WWW-Authenticate: Negotiate

WWW-Authenticate: NTLM

Connection: close

Content-Length: 4431

Content-Type: text/html

}

Here is the code I'm using. Any help would really be appreciated.

var client = new HttpClient { BaseAddress = new Uri(_uri) };

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var response = client.GetAsync(string.Format("api/Config/{0}", id)).Result;

if (response.IsSuccessStatusCode)
{
    var res = response.Content.ReadAsAsync<int>().Result;
    return res;
}

As the response indicates you are not authorized to access the resource probably because you are not passing in proper credentials. Looks like your service is enabled with Windows Authentication. Try doing the following and see if it works:

HttpClientHandler hndlr = new HttpClientHandler();
hndlr.UseDefaultCredentials = true;
var client = new HttpClient(hndlr) { BaseAddress = new Uri(_uri) };

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