HTTP POST正在提供未经授权的401例外

时间:2013-11-19 13:35:08

标签: c# asp.net json post

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

但是当我尝试在codebehind(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;

        }

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

1 个答案:

答案 0 :(得分: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);
这对我有用。希望这会对你有所帮助。