Question

I am using C# with RestSharp to make some calls to a rails application. But it seems the session variables are not saved when doing this. It works fine when using a normal browser to make the calls.

This is my call in c#

 public void createUser(String firstname, String lastname, String password)
        {
            RestClient client = new RestClient("http://localhost:3000");
            RestRequest request = new RestRequest("users/login/{firstname}/{lastname}/{password}", Method.GET);
            request.AddUrlSegment("firstname", "admin");
            request.AddUrlSegment("lastname", "admin");
            request.AddUrlSegment("password", "admin");

            IRestResponse response = client.Execute(request);
            var content = response.Content;

            RestRequest request2 = new RestRequest("users/create/{firstname}/{lastname}/{password}", Method.GET);
            request2.AddUrlSegment("firstname", "this");
            request2.AddUrlSegment("lastname", "will");
            request2.AddUrlSegment("password", "work");

            response = client.Execute(request2);
            content = response.Content;
            MessageBox.Show(content);

        }

And here are the rails methods:

 def create
    firstname = params[:firstname]
    lastname = params[:lastname]
    pwd = params[:password]
    @user = User.new({:firstname => firstname, :lastname => lastname, :password => pwd })
    @userloggedin = User.find(session[:user_id])

    if(@userloggedin.is_admin == 1)

      respond_to do |format|
        if @user.save
          format.html { redirect_to "http://google.com" }
          format.json { render json: "user created" } 
        end
      end



    end
  end






  def login
    firstname = params[:firstname]
    lastname = params[:lastname]
    password = params[:password]

    @user = User.where("firstname = ? AND lastname = ?", firstname, lastname).first

    if(@user && @user.password == password)
      session[:loggedin] = true
      session[:user_id] = @user.id
      respond_to do |format|
        format.html { redirect_to "http://google.com" }
        format.json { render json: "accpeted" }
      end
    else

      respond_to do |format|
          format.html { redirect_to "http://google.com" }
          format.json { render json: "not accpeted" }
    end

  end

WHen making the second call in c# i get: ActiveRecord::RecordNotFound\n in UsersController#create\n

Couldn't find User without an ID

because the session variable was not saved.

Is there any way to make it work with a nonbrowser client?

Was it helpful?

Solution

In order to preserve Session, the client needs to hold the information. Browsers do it via cookies.

For RestSharp, try using CookieContainer to hold the cookie information between calls. Reference here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top