Tonight i come search some help about how to call a web api hosted in IIS.
Everything work well in local from visual studio to iis express. But strangely, after publish on my IIS server. I always get 401 unauthorized :'(
Here is the code i use and the settings from my IIS server. I will be very grateful if somebody can help me. Thank you
**
**
[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;
}
**
**
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;
}
**
**
**
**
Finally after search many times , many houres by myself. I find the solution. We should never enable Basic Authentication.... I know it's weird ^^ But if you want to use your custom basic authentication. Just disabled the Basic Authentication on IIS and everything goes well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With