cancel
Showing results for 
Search instead for 
Did you mean: 

Consuming oData for function import using Javascript or C#

CRVMANISH
Contributor
0 Kudos

Hello Experts,

Below URL works fine from REST Client when tested but we are not able to do it in C# or Javascript.

http://115.111.213.74:8000/sap/opu/odata/sap/ZWRK_CTR_GW_SRV/ZWRK_CTR?IsNotifNo='000300000131'&IsPla...

The Get Method work fine for getting  x-csrf-token value, but using the token we are getting error for POST method.

Please provide any code snippet for using above URL which is developed using function import to POST the data using x-csrf-token value

for C# or JavaScript.

Please Suggest

Regards

Manish

Accepted Solutions (0)

Answers (1)

Answers (1)

kammaje_cis
Active Contributor
0 Kudos

Hi Manish,

Here you find code for Javascript.

http://scn.sap.com/community/developer-center/front-end/blog/2012/06/06/sample-ume-application-using...

You have code for

1. Issuing Get request to fetch the csrf token

2. Get the token value

3. Issue a Post request.

Thanks

Krishna

CRVMANISH
Contributor
0 Kudos

Hello Krishna,

In the blog it is not mentioned how user credentials are passed.

Regards

Manish

former_member184867
Active Contributor
0 Kudos

Hi Manish,

Use the following code

OData.request 

({  

requestUri: "http://gwserxzver:8000/sap/opu/odata/sap/Z_UI5_USER_MAINT_CM/z_ui5_user_maintCollection('AGAMPA')",  

method: "GET",  

user: 'Joe', password: 'Soap'

headers:  

{       

                        "X-Requested-With": "XMLHttpRequest", 

                        "Content-Type": "application/atom+xml", 

                        "DataServiceVersion": "2.0",          

                        "X-CSRF-Token":"Fetch"      

} },  )

This is a Datajs notation. Please fine more in the following forum

http://datajs.codeplex.com/discussions/269403

Regards,

Atanu

CRVMANISH
Contributor
0 Kudos

Hello Aatanu & Krishna,

This is my URL

http://115.111.213.74:8000/sap/opu/odata/sap/ZWRK_CTR_GW_SRV/ZWRK_CTR?IsNotifNo='000300000131'&IsPla...

It works fine from REST client.

'It give error as Access to Restricted URI Denied' or 'Http Request failed'

Below is the code, suggest what is wrong here

Function gettoken(key, ostr) {

    try {

        var aostr = [];

        aostr = ostr.split(',');

        var req_ser = "http://115.111.213.74:8000/sap/opu/odata/sap/ZWRK_CTR_GW_SRV/ZWRK_CTR";

        var sdata = {

            IsNotifNo: "000300000131",

            IsPlant: "0001",

            IsWrkCtr: "CENTER2"

        };

        var request = {

            method: "POST",

            user: 'xxxxx,

        password:'xxxxx',

            headers: {

                "X-Requested-With": "XMLHttpRequest",

                "Content-Type": "application/atom+xml",

                "DataServiceVersion": "2.0",

                "X-CSRF-Token": key

            },

            requestUri: req_ser,

            data:sdata                     

        };

        OData.request(

request,

function (data) {

    alert('done');

},

function (err) { //Error Callback: alert("Error occurred " + err.message);

    alert(err.message);

}

);

    } catch (ex)

{alert(ex);}

}

former_member184867
Active Contributor
0 Kudos

Hi,

This can be CORS issue.

Can you post a screenshot of the error from Chrome developer console ?

Regards,

atanu

CRVMANISH
Contributor
0 Kudos

Regards

Manish

former_member184867
Active Contributor
0 Kudos

Can you post a screenshot of the error from Chrome developer console ?

CRVMANISH
Contributor
0 Kudos
former_member184867
Active Contributor
0 Kudos

This is due to CORS issue. For details you can do a search on Google.

For now, I can suggest the following steps

1. From the Task Manager Kill all the processes related to Google Chrome.

2. Go to Command Prompt, and execute command  "

cd C:\Program Files (x86)\Google\Chrome\Application"  (assuming that your chrome is installed in C:\Program Files (x86)\Google\Chrome\Application location )

3.Then execute 'Chrome.exe --allow-file-access-from-files --disable-web-security'

This will disable the chrome security and will launch the chrome. On the start up you will notice a warning message regarding this.

Then you will be able to fire the URL from the browser without CORS Issue

CRVMANISH
Contributor
0 Kudos

Atanu

Still getting same problem

Regards

Manish

kammaje_cis
Active Contributor
0 Kudos

Did you get the warning when you opened Chrome?

If not, Chrome has not taken it into consideration the commend which you gave.

Close (exit) all the Chrome browsers. Ensure in the task manager that no Chrome related task is still open. Now open Chrome as Atanu suggested. It should work.

Thanks

Krishna

CRVMANISH
Contributor
0 Kudos

Yes , I get the warning but still i  receive same error Http request failed.

can you please check code once which i have pasted above.

Regards

Manish

CRVMANISH
Contributor
0 Kudos

Now i get following , does it has something to do with cookies

Regards

Manish

kammaje_cis
Active Contributor
0 Kudos

See the network tab for exact response from the service. That will tell the reason for 'forbidden;. It is mostly due to login/password/authorization issue.

Former Member
0 Kudos

hi Manish,

Did you find a solution? I'm facing the same problem with a C# call.

My Gateway service POST operation works (tested with the Firefox REST client).

The C# GET requests work.

For the POST request, I first do a Get request with header X-CSRF-Token: Fetch

With Fiddler I can see the token is returned by SAP.

Then I do a POST request with that token, however I get the status code: 403 Forbidden (
Validierung des CSRF-Tokens fehlgeschlagen). It seems the SAP "session" is closed and the token is not valid anymore.

Regards

Frank

CRVMANISH
Contributor
0 Kudos

Hello Frank,

I am having exactly same issue, i had to do it via Java Script for POST method and it worked.

Let me know if you find solution.

Its not related to expired token , it is CORS issue.

You can try disabling your security setting of firefox.

Regards

Manish

CRVMANISH
Contributor
0 Kudos

Hello Frank,

403 errror is most of the time related to cookies , u need to clear it.

Read Below

The application connection ID of a previous request has been stored as a Cookie in the browser and the SMP is preventing the request to add a new connection with an ID that already exists.


Former Member
0 Kudos

Hi Manesh

I solved the 403 forbidden error, but no I'm facing a 500 internal server error. The Gateway error log shows the following error: "The Data Services Request could not be understood due to malformed syntax"

That error is because of the outdated Visual Studio developer tool I think.

The XML of the Gateway request is "created" via an object of a class generated by the Visual Studio Gateway plugin. In the created XML, the attribute/value m:null="true" is added for null fields.

For example: <d:Message m:null="true" />

This was correct for older Gateway versions, but as of GW 2.0 SP03 I think, it has to be <d:Message/>

Fyi, the 403 forbidden error was because of a cookie issue. Below some code snippets:

1. A GET request with the header value: X-CSRF-Token: Fetch

            ...

            //Get CSRF token

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri(gwUrl));

            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(gwuser, gwpw);

            req.Credentials = credentials;

            req.Method = "GET";

            req.Headers.Add("X-CSRF-Token", "Fetch");

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            this.csrfToken = resp.Headers.Get("X-CSRF-Token");

             ...

2. The CSRF token is validated against the anti-csrf cookie. So the cookies of the first GET request have to be added to the POST request

                    ...

                    foreach (Cookie cookieValue in resp.Cookies)

                    {

                         Cookie cookvalue = cookieValue;

                         cookieJar.Add(cookvalue);

                    }

                    ...
                    gwClient.SendingRequest += new EventHandler<System.Data.Services.Client.SendingRequestEventArgs>(gwClient_SendingRequest);

                    try

                    {

                          gwClient.SaveChanges();

                    }

                    catch (Exception ex)

                    {

                    }

                    ...

          void gwClient_SendingRequest(object sender, SendingRequestEventArgs e)

          {

            if (this.csrfToken != String.Empty)

            {

                e.RequestHeaders.Add("X-CSRF-Token", this.csrfToken);

                e.Request.ContentType = "application/atom+xml; type=entry";

                e.Request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(gwuser + ":" + gwpw)));

                ((HttpWebRequest)e.Request).CookieContainer = cookieJar;

            }

          }

former_member198924
Participant
0 Kudos

Hi Schepers

I am trying to do the same process, If you have a solution please share for posting. I am able to get token but posting data is giving me 403 error, you can see my code here..

xml - C# post using xcsrf token - Stack Overflow

di_deng
Explorer
0 Kudos

Hi Schepers, Thank you for pointing out that storing the cookies is the solution. It's inspiring and finally I solved the issue.