【发布时间】:2016-12-14 18:53:19
【问题描述】:
今晚我来搜索一些关于如何调用托管在 IIS 中的 web api 的帮助。
在本地,从 Visual Studio 到 iis express,一切正常。但奇怪的是,在我的 IIS 服务器上发布后。我总是得到未经授权的 401 :'(
这是我使用的代码和来自我的 IIS 服务器的设置。如果有人可以帮助我,我将不胜感激。 谢谢
**
我尝试调用的控制器和函数(具有基本身份验证属性)
**
[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 - 集成)
**
提琴手调试
【问题讨论】:
-
能贴出代码吗?
-
请不要将您的代码显示为图片。请编辑您的问题,将其替换为从 IDE 剪切和粘贴的代码。完成后,选择它并按 Ctrl-K 将其格式化为代码块。
-
对不起,我可以,我现在才更新。但正如我所见,该代码在(本地)模式下工作得很好。也许问题出在我的 IIS 服务器上
标签: c# asp.net-web-api asp.net-web-api2 basic-authentication