我有一个需要访问REST ArcGIS服务的.NET应用程序。此服务是私有服务,需要基于令牌的身份验证才能访问服务中的数据。由于我不熟悉ArcGIS,因此我不知道如何生成令牌并在我的.NET应用程序中使用它。
答案 0 :(得分:1)
如果您想要简单的http请求,可以创建一个简单的连接以遵循以下内容。
首先,您必须知道生成令牌网址。 例如,如果您的服务器网址为http://myserver/arcgis/rest/services ....,您的生成令牌网址就像“http://myserver/arcgis/tokens/generateToken”。 第二个操作是为生成令牌结果准备结果模型,它就像下面的
/// <summary>
/// acgis'e yapılan token isteme isteği sonunda elde edilen json'a ait modeldir
/// </summary>
public class ArcgisTokenResponseModel
{
/// <summary>
/// token bilgisi
/// </summary>
public string token { get; set; }
/// <summary>
/// token bilgisinin geçerlilik süresi
/// </summary>
public string expires { get; set; }
}
对于可重用代码,我们可以创建准备查询字符串键值的类。 这个课程就像下面的
/// <summary>
/// arcgis yapısına uygun token modelidir
/// </summary>
public class TokenModel
{
/// <summary>
/// servisin dönüş tipini belirleyen fieldttır . ör ; json,html
/// </summary>
public string f { get; set; }
/// <summary>
/// servise gönderilecek kullanıcı adı bilgisi
/// </summary>
public string username { get; set; }
/// <summary>
/// servise gönderilecek olan şifre bilgisidir.
/// </summary>
public string password { get; set; }
/// <summary>
/// token bilgisinin hangi ip için geçerli olacağını bildirir
/// </summary>
public string ip { get; set; }
/// <summary>
/// token bilgisinin ne kadar süreli olacağını belirtir
/// </summary>
public int expiration { get; set; }
/// <summary>
/// servis client bilgisi
/// </summary>
public string client { get; set; }
/// <summary>
/// constructure
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="ip"></param>
/// <param name="expiration"></param>
/// <param name="f"></param>
public TokenModel(string username, string password, string ip, int expiration, string f = "json")
{
this.expiration = expiration;
this.f = f;
this.ip = ip;
this.password = password;
this.username = username;
}
/// <summary>
/// modelin query string halinde dönüşünü sağlar
/// </summary>
/// <returns></returns>
public string GetQueryStringParameter()
{
return "f=" + this.f + "&username=" + this.username + "&password=" + this.password + "&ip=" + this.ip + "&expiration=" + this.expiration;
}
}
然后准备一个使用用户名和密码从arcgis服务器生成令牌的函数。这个功能可能喜欢这个
/// <summary>
/// mapserver ve feature server için token bilgisi üretir
/// </summary>
/// <returns></returns>
protected string GetToken(string generateTokenUrl,string username,string password)
{
try
{
string ipadress = _serverInformationHelper.GetIPAddress();
int exp = 60;
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
Model.Arcgis.TokenModel tokenModel = new Model.Arcgis.TokenModel(username, password, ipadress, exp);
//token bilgisinin alınacağı server url'i
string post = tokenModel.GetQueryStringParameter();
WebClient clientToken = new WebClient();
clientToken.Headers.Add("Content-Type: application/x-www-form-urlencoded");
string tokenResult = clientToken.UploadString(generateTokenUrl, post);
ArcgisTokenResponseModel resultTokenModel = _seriliazer.Deserialize<ArcgisTokenResponseModel>(tokenResult);
if (resultTokenModel != null && !string.IsNullOrEmpty(resultTokenModel.token))
return resultTokenModel.token;
}
return null;
}
catch (Exception ex)
{
return null;
}
}
毕竟,无论你想要什么,你都可以使用GetToken()函数。如果需要,我们可以简化操作。
祝你好运
答案 1 :(得分:1)
正如@spiskula所提到的,你可以按照https://github.com/Esri/resource-proxy/blob/master/DotNet/proxy.ashx中显示的方法,特别是getNewTokenIfCredentialsAreSpecified方法。
这是一个非常简单的例子(pre .Net 4.5),在没有SDK的情况下做同样的事情。用户需要通过错误处理等方式使其更加健壮。
private string GetToken()
{
var request = (HttpWebRequest)WebRequest.Create("https://www.arcgis.com/sharing/rest/oauth2/token/");
var postData = "client_id=yourclientid"; //required
postData += "&client_secret=yourclientsecret"; //required
postData += "&grant_type=client_credentials"; //required
postData += "&expiration=120"; //optional, default
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
ESRITokenResponse eToken = Newtonsoft.Json.JsonConvert.DeserializeObject<ESRITokenResponse>(responseString);
return eToken.access_token;
}
public class ESRITokenResponse
{
public string access_token { get; set; }
public string expires_in { get; set; }
}
答案 2 :(得分:0)
有关概述,请参阅https://developers.arcgis.com/authentication/accessing-arcgis-online-services/#using-rest。有两种选择:
这是一个使用硬编码登录的ArcGIS Runtime SDK for .NET示例。我上面链接的.NET页面也有一个样本,它向用户提出挑战凭证。
try
{
var opts = new GenerateTokenOptions();
opts.TokenAuthenticationType = TokenAuthenticationType.ArcGISToken;
// generate an ArcGIS token credential with a hard-coded user name and password
// (if authentication fails, an ArcGISWebException will be thrown)
var cred = await IdentityManager.Current.GenerateCredentialAsync(
"http://serverapps10.esri.com/arcgis/rest/services/",
"user1",
"pass.word1",
opts);
// add the credential to the IdentityManager (will be included in all requests to this portal)
IdentityManager.Current.AddCredential(cred);
// load a layer based on a secured resource on the portal
var layer = new ArcGISDynamicMapServiceLayer(new Uri
("http://serverapps10.esri.com/arcgis/rest/services/GulfLawrenceSecureUser1/MapServer"));
await layer.InitializeAsync();
// add the layer to the map and zoom to its extent
this.MyMapView.Map.Layers.Add(layer);
await this.MyMapView.SetViewAsync(layer.FullExtent);
}
catch (ArcGISWebException webExp)
{
MessageBox.Show("Unable to authenticate with portal: " + webExp.Message);
}
catch (Exception exp)
{
MessageBox.Show("Unable to load secured layer: " + exp.Message);
}
答案 3 :(得分:0)