簡體   English   中英

使用基本身份驗證調用web api始終從IIS中獲取401未授權

[英]Call web api with basic authentication always get 401 unauthorized from IIS

今晚我來搜索一些關於如何調用IIS中托管的web api的幫助。

從視覺工作室到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 - 集成)

** 在此輸入圖像描述

**

提琴手調試

** 在此輸入圖像描述

最后經過多次搜索,很多人都是我自己。 我找到了解決方案。 我們永遠不應該啟用基本身份驗證....我知道這很奇怪^^但是如果你想使用自定義基本身份驗證。 剛剛在IIS上禁用了基本身份驗證 ,一切順利。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM