Search code examples
restasp.net-web-apisalesforcetokenhttp-status-code-401

Salesforce rest api INVALID_SESSION_ID


I'm trying to connect my asp.net REST api to salesforce. I'm succesfully going through authentification, but when I start to send POST requests, I'm getting an error

{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}

Here is my POST request:

    //SFServerUrl = "https://na17.salesforce.com/services/";
    //url = "data/v28.0/sobjects/Account";

            ASCIIEncoding ascii = new ASCIIEncoding();
            byte[] postBytes = ascii.GetBytes(postBody);
            HttpWebRequest request = WebRequest.Create(Globals.SFServerUrl + url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = postBytes.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);

            HttpCookie cookie = HttpContext.Current.Request.Cookies[Globals.SFCookie];
            var ticket = FormsAuthentication.Decrypt(cookie.Value);
            string authToken = ticket.UserData;
            request.Headers.Add("Authorization", "Bearer " + authToken);
            postStream.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[8192];
            Stream resStream = response.GetResponseStream();
            string tempString = null;
            int count = 0;
            do
            {
                count = resStream.Read(buf, 0, buf.Length);
                if (count != 0)
                {
                    tempString = Encoding.ASCII.GetString(buf, 0, count);
                    sb.Append(tempString);
                }
            }
            while (count > 0);
            return new Tuple<bool, string>(true, sb.ToString());

When I'm trying to send GET request - I recieve 200 response. Also, I've tried to send a POST Request with the same token from Simple Rest Client and it get's 200 response. I tried to change my "Authorization : Bearer" Header to "Authorization : Oauth", but nothing changed. I also tried to catch this error, get refresh token and send a request again with refreshed token, but nothing changed. Please, help me with this.


Solution

  • The problem was that I added Headers after Content. When I switched these lines of code everything worked.