Consuming Drupal RestApi with c#

2019-09-12 15:46发布

问题:

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 google's postman to post the content but when I try to replicate it with c# code I am prompted with forbidden error saying: Access denied for user anonymous. I am utilising rest-sharp to consume this API. I have researched quite a lot and haven't found solution yet,as well as haven't noticed anyone doing this work in c#. Following is the code snippet that I have written based on postman


        var client = new RestClient("drupasitename/rest/node");
        var request = new RestRequest(Method.POST);

        request.AddHeader("cache-control", "no-cache");
        request.AddHeader("authorization", authorisation);
        request.AddHeader("x-csrf-token", token);
        request.AddHeader("cookie", cookie);
        request.AddHeader("content-type", "application/json");
        request.AddHeader("Accept", "application/json");
        request.AddParameter("application/json", "{\r\n  \"type\":\"page\",\r\n  \"title\":\"Page submitted via JSON REST\",\r\n  \"body\":{\r\n    \"und\":[\r\n      {\r\n        \"value\":\"This is the body of the page.\"\r\n      }\r\n    ]\r\n  }\r\n}", ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

cookie and token are obtained after successful login attempt using c# code.

It would be great if anyone could provide a guidance to solve this issues. Regards

回答1:

All you need is adding UserAgent into http request header



回答2:

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)



回答3:

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