I am working to consume Drupal Rest Api using c#. I am using drupal 7.5 and utilising it\'s rest services/api following various resources.
I have been successful with go
I got the user information include the cookie & token .
private login_user LoginAsync(string username,string password)
{
try
{
RestClient client = new RestClient(base_url);
var request = new RestRequest("login", Method.GET);
request.AddHeader("Content-Type", "Application/JSON");
client.Authenticator = new HttpBasicAuthenticator(username, password);
var restResponse = client.Execute(request);
var content = restResponse.Content;
string context_modifytoken = content.ToString().Replace("X-CSRF-Token", "X_CSRF_Token");
var current_login_user = JsonConvert.DeserializeObject<login_user>(context_modifytoken);
current_login_user.data.session_name = restResponse.Cookies[0].Name;
current_login_user.data.session_id = restResponse.Cookies[0].Value;
return current_login_user;
}
catch (HttpRequestException ex) { throw ex; }
}
And the Post section:
RestClient client = new RestClient(base_url);
var request = new RestRequest("v1.0/barcodes", Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("X-CSRF-Token", current_user.data.X_CSRF_Token);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddHeader("cookie", current_user.data.session_name+"="+ current_user.data.session_id);
request.AddHeader("User-Agent", ver);
var queryresult = client.Execute(request);
has error :queryresult = "StatusCode: Forbidden, Content-Type: application/problem+json; charset=utf-8, Content-Length: -1)"
and Drupal log : restful 2016-09-21 16:32 You do not have access to create a new Sample Barcode... Anonymous (not verified)
All you need is adding UserAgent into http request header
I used following to login to drupal
var client = new RestClient("drupalsitename/user/login");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
request.AddParameter("application/json", "{\"name\":\"username\",\n\"pass\":\"password\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This will provide you with necessary session and token info and then basically you can use those information to make the post, similar to that I have written in the question