【问题标题】:HTTP POST is giving unauthorized 401 ExceptionHTTP POST 给出未经授权的 401 异常
【发布时间】:2013-11-20 17:12:15
【问题描述】:

登录后在google chrome postman 上调用相同的方法时,我得到的json 对象如下所示。

但是当我尝试在代码隐藏 (C#) 中获得相同的 json 结果时。我收到未经授权的 401 异常。

我正在这样使用我的代码。

using (var clientSideTab = new WebClient())
        {

            var valSideTab = new System.Collections.Specialized.NameValueCollection { { "username", UserID }, { "Password", strPassword } };
            string UpldDataSideTab = "https://resapistage.namechanged.com/v3/secure/Login.aspx?userId=" + UserID + "&passwd=" + strPassword + " ";                                                

            SystemComponentWrapper SPPostWrapper = new SystemComponentWrapper();
            SystemComponentData request = new SystemComponentData();
            SystemComponentaddressId addressId = new SystemComponentaddressId();

            addressId.type = "AddressId";
            addressId.id = 19863;
            addressId.serial = "";

            request.addressId = addressId;
            request.compId = null;
            request.getCompParams = true;
            request.filterForAddress = false;

            SPPostWrapper.request = request;

            var postJson = JsonConvert.SerializeObject(SPPostWrapper);
            Encoding encoding = new UTF8Encoding();
            string postData = postJson.ToString();
            byte[] bdata = encoding.GetBytes(postData);


            string URI = "https://resapistage.namechanged.com/v3/api/secure/json/AddressInfo.svc/getSystemComponentsV2";
            clientSideTab.UploadValues(UpldDataSideTab, "POST", valSideTab);


            clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
            clientSideTab.Headers.Add("Accept","application/json");                
            clientSideTab.UploadString(URI,"POST", postData);
            //clientSideTab.UploadData(URI, "POST", bdata);

            String jsonresponse = "failed";


            Label1.Text = jsonresponse;

        }

我每次都收到此错误。请帮我。

【问题讨论】:

  • 网站是否需要身份验证?您在进行 chrome 调用时是否经过身份验证?通过 C# 调用,您是否发送了显示您已通过身份验证的 cookie?
  • 如何在webclient中发送cookie和json数据来获取json响应?
  • 谷歌搜索让我想到了这个 Stack Overflow 问题:stackoverflow.com/questions/13275042/add-cookie-to-webclient

标签: c# asp.net json post


【解决方案1】:

这样使用。

            string cookie = strCookie[0]; // fetch your cookie after logging in
            clientSideTab.Headers.Add("Content-Type","application/json; charset=utf-8");
            clientSideTab.Headers.Add("Accept","application/json");
            clientSideTab.m_container.SetCookies(URI, cookie);
            //clientSideTab.Headers.Add(HttpRequestHeader.Cookie, cookie);
            String resultJSON = clientSideTab.UploadString(URI,"POST", jsonData);

这对我有用。希望这会对你有所帮助。

【讨论】:

  • 是的,在谷歌上搜索了很多之后,我已经实现了这个。无论如何,谢谢你的努力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 2012-07-17
  • 2017-12-27
  • 2017-03-16
  • 2017-12-20
相关资源
最近更新 更多