Select to view content in your preferred language

Generate Token to Access AGOL Feature Service using C#

502
0
10-04-2021 05:49 PM
JenniferLink1
New Contributor III

Hello,

I need to add features to a feature service that is hosted in AGOL and shared with my organization. I am trying to do this through a client application using the ArcGIS REST endpoint. I have not been able to retrieve a token using a web request with C#. I can send a request through the browser successfully using:

https://www.arcgis.com/sharing/generateToken?f=json&username=MYUSERNAME&password=MYPASSWORD&client=r...

However, when I attempt this using a web request through code, I get an error that the username and password are required.

Here is the code:

string tokenString = "https://www.arcgis.com/sharing/generateToken?f=json&client=requestip";

HttpWebRequest tReq = WebRequest.Create(new Uri(tokenString)) as HttpWebRequest;
tReq.Method = "POST";
tReq.ContentType = "application/json";

SecureString securePass = new SecureString();
foreach (char c in MYPASSWORD.ToCharArray()) securePass.AppendChar(c);

tReq.Credentials = new NetworkCredential() { UserName = MYUSERNAME, SecurePassword=securePass };

byte[] formDataToken = UTF8Encoding.UTF8.GetBytes(tokenString);

using (Stream posttoken = tReq.GetRequestStream())
{
      posttoken.Write(formDataToken, 0, formDataToken.Length);
}

string resultToken = null;
using (HttpWebResponse respToken = tReq.GetResponse() as HttpWebResponse)
{
     StreamReader readerToken = new StreamReader(respToken.GetResponseStream());
     resultToken = readerToken.ReadToEnd();
}

The error I am getting is:

{"error":{"code":400,"message":"Unable to generate token.","details":["'username' must be specified.","'password' must be specified."]}}

I have read the threads, and looked at the examples in GitHub, and Googled as much as I can, and I am still stuck. Anyone have experience with this?

Thanks!

Jen

 

0 Kudos
0 Replies