将HttpRequest发送到SFDC Web服务时传递登录信息

时间:2013-06-12 17:45:20

标签: c# login salesforce httprequest

尝试将JSON HttpRequest发送到SFDC Web Service,得到以下响应:

[1]
0:  {
message: "Session expired or invalid"
errorCode: "INVALID_SESSION_ID"
}

如何使用HttpRequest正确地从LoginResult传递会话ID或其他信息?代码示例如下:

    // Generate JSON
    MyClass object = new MyClass();
    string post_data = JsonSerializer.SerializeToString(object);   // this is what we are sending

    // this is where we will send it
    string uri = "https://url.salesforce.com/some_path/";

    // create a request
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.KeepAlive = false;
    request.Method = "POST";
    byte[] postBytes = Encoding.ASCII.GetBytes(post_data);
    request.ContentType = "application/json";
    request.ContentLength = postBytes.Length;

    // Setup proxy and SFDC login
    LoginResult result = SfdcConnection.GetLoginResult();
    // ------------ Need to add login info here -----------------

    // now send it
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(postBytes, 0, postBytes.Length);
    requestStream.Close();

    // grab te response and print it out to the console along with the status code
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string jsonResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();

2 个答案:

答案 0 :(得分:1)

你需要使用oauth模式在Authorization标头中传递sessionId,所以它是

request.Headers.Add("Authorization", "Bearer " + result.sessionId);

sessionId可以使用很长一段时间,所以只需要调用一次登录,而不是在每次REST api调用之前。

REST API docs中详细介绍了这一点。

答案 1 :(得分:0)

您需要将LoginResult(很可能包含会话ID)附加到您的请求中,否则,Web服务只会看到没有会话ID的请求(也没有cookie),并且无法使用验证您是登录的客户端。

伪代码

LoginResult result = SfdcConnection.GetLoginResult();
// attach sesionId to your request, see the web services documentation for this
request.Headers.Add("sessionId", result.sessionId);