cancel
Showing results for 
Search instead for 
Did you mean: 

C# CRUD operation for SAP GAteWay

pkb
Participant
0 Kudos

Dear All

Can you help us with codes or information about how to consume Odata service of SAP gateway  from Web Application developed in C# . We are able to do read operation (GET) but failed for POST or PUT. I have followed the link http://scn.sap.com/community/gateway/blog/2012/04/26/modifying-request-through-gateway-using-net-c

Though we have tried many times after following the above link's information , we failed for POST/PUT operation because of CSFR Token validation failed . We are also aware about " How to deactivate CSRF token validation" by setting parameter 0 in ~CHECK_CSRF_TOKEN. But we want to do POT/PUT with CSRF validation .

Also want to state that When we can do successfully  the POST operation using FireFox REST tool with CSRF token .

Please help us with information or codes for C#

-pk

Accepted Solutions (0)

Answers (3)

Answers (3)

Former Member
0 Kudos

Have the same problem, sending(using post method) the xcrf token received by get method. Have you got the solution, if so please help..

lynn_lin
Active Participant
0 Kudos

Hi,

Please refer to

Regards,

Lynn

former_member206574
Active Participant
0 Kudos

Hi PK,

Before doing POST/PUT operation u have to fetch the X-CSRF-Token by using GET operation Service and pass the fetched X-CSRF-Token to Request header in POST/PUT operation

Regards,

Venu

Former Member
0 Kudos

PK, would you be able to post your code snippet that is building the Request header and also the response headers.  This is the easiest to know what is wrong with your code.

pkb
Participant
0 Kudos

Hello  Ramprasad,

Sorry for the late reply,

Below is the code in C# written using VS 2012. I just followed the link http://scn.sap.com/community/gateway/blog/2012/04/26/modifying-request-through-gateway-using-net-c  to write my codes. I am trying to do POST operation . But received 403 error. When I checked in Fiddler then found that although  we have send in the Header request POST /sap/opu/odata/sap/ZEMPMASTER_SRV/ZEMPMASTERSet HTTP/1.1  the x-csrf-token but in response , its asking again the x-csrf-token . In debug mode of  c# , we found that the exception is "csrf token validation is failed" . So we are not able to under stand how to over come this problem.

Codes:-

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.Data;

using System.Data.Services.Client;

namespace WebApplication2

{

 

    public partial class WebForm1 : System.Web.UI.Page

    {

 

        public string csrfToken = String.Empty;

        public string setCookie = String.Empty;

        public CookieContainer cookieJar = new CookieContainer();

        public void materialClient_SendingRequest(object sender, System.Data.Services.Client.SendingRequestEventArgs e)

        {

            // If we have a CSRF token, add it to the request headers. Make sure to set Content-               Type in headers to correct value.  

            if (this.csrfToken != String.Empty)

             e.RequestHeaders.Add("x-csrf-token", this.csrfToken);  

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

// Append cookies from response above to modifying request.           
CookieCollection cookies = cookieJar.GetCookies(new Uri("http://xx.xx.xx.xx:8000/sap/opu/odata/sap/ZEMPMASTER_SRV/"));

            foreach (Cookie cookie in cookies)

            {

               e.RequestHeaders.Add("Cookie", cookie.ToString());           

            }

 

        }

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        protected void Button1_Click(object sender, EventArgs e)

        {

 

            // Setup network credentials object to be used for requests to Gateway server 

            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("userid", "password");

            //Create Gateway objects 

            Uri uri = new Uri(http://xx.xx.xx.xx:8000/sap/opu/odata/sap/ZEMPMASTER_SRV/);

            var container = new EmpSrv.ZEMPMASTER_SRV_Entities(uri);

          
                   container.Credentials = credentials;

            // Check to see if we already have the CSRF token...if not, request it from the server. 

            if (this.csrfToken == String.Empty)

            {

                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);

               
                HttpWebResponse resp;

                // Add custom header request to fetch the CSRF token

              
               req.Credentials = credentials;

              
req.Method = "GET";

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

                // Setup cookie jar to capture cookies coming back from Gateway server. These
cookies are needed along with the CSRF token for modifying requests. 

              
cookieJar = new CookieContainer();
req.CookieContainer = cookieJar;

                try

                {

                  
                    resp = (HttpWebResponse)req.GetResponse();

                }

                catch (System.Net.WebException ex)

                {

                    //Add your error handling here 

                  
                         return;

                }

                catch (Exception ex)

                {

                    //Add your error handling here 
                    return;

                }

                // Assign values from response to class variables. 

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

              
this.setCookie = resp.Headers.Get("Set-Cookie");

            }

            // Assign values to objects being passed into Gateway request. 

            var row2 = new EmpSrv.ZEMPMASTER();

          
               row2.EmpCode = "353";

          
               row2.EmpName = "Test Employee Name";

          
               row2.EmpSalary = "2341";

            // commented out rest of value assignment for brevity 

            // Use native .NET data service client to build request to add item to collection
(CREATE/POST) 

          
container.AddToZEMPMASTERSet(row2);

            // Add event handler to add additional data to service request 

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

            // Post changes to GW server 

            try

            {

                
                    container.SaveChanges();              

            }

            catch (Exception ex)

            {

                //Add your error handling here 

            }   

        }

    }

}