今晚我来搜索一些关于如何调用 IIS 中托管的 web api 的帮助。
在本地从 visual studio 到 iis express,一切正常。但奇怪的是,在我的 IIS 服务器上发布之后。我总是得到 401 unauthorized :'(
这是我使用的代码和我的 IIS 服务器的设置。如果有人能帮助我,我将不胜感激。 谢谢
**
我尝试调用的 Controller 和函数(具有基本身份验证属性)
**
[HttpGet]
[ActionName("Get_UserID")]
[IdentityBasicAuthentication]
[Authorize]
public HttpResponseMessage Get_UserID(string userName)
{
HttpResponseMessage res = new HttpResponseMessage(HttpStatusCode.Created);
try
{
var user = Membership.GetUser(userName, false);
if (user != null)
{
res = Request.CreateResponse(HttpStatusCode.OK, (Guid)user.ProviderUserKey);
}
else
{
res = Request.CreateResponse(HttpStatusCode.ExpectationFailed);
res.Content = new StringContent("Error");
res.ReasonPhrase = "UserName not find in the database";
}
}
catch (Exception exc)
{
//Set the response message as an exception
res = Request.CreateResponse(HttpStatusCode.InternalServerError);
res.Content = new StringContent("Exception");
res.ReasonPhrase = exc.Message;
}
return res;
}
**
客户端 - 我如何调用 web api 并构建我的 httpClient
**
public static async Task<HttpResponseMessage> RequestStart(string requestUrl, string webApiUrlBase = Globals.WebApi_Url, bool IsAuthenticateMemberRequest = false)
{
if (webApiUrlBase == null)
{
webApiUrlBase = Globals.WebApi_Url;
}
var response = new HttpResponseMessage(HttpStatusCode.Created);
using (var client = new HttpClient())
{
if (IsAuthenticateMemberRequest)
{
string strToEncode = ApplicationData.Current.LocalSettings.Values["userName"].ToString() + ":" + ApplicationData.Current.LocalSettings.Values["password"].ToString();
var authenticationBytes = Encoding.ASCII.GetBytes(strToEncode);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
}
client.BaseAddress = new Uri(Globals.WebApi_Url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await client.GetAsync(requestUrl);
}
return response;
}
**
IIS 配置(appPool => NetworkServices - 集成)
**
Fiddler 调试
最佳答案
终于自己找了好多次,好几个小时。我找到了解决办法。我们永远不应该启用基本身份验证.... 我知道这很奇怪 ^^ 但是如果你想使用你的自定义基本身份验证。只需在 IIS 上禁用基本身份验证,一切顺利。
关于c# - 使用基本身份验证调用 web api 总是从 IIS 获得 401 未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38838665/