Ashraful, 22, and 18-year-old Rahim defied the Sri Lankan bowlers with grit and determination to add 96 for the undefeated sixth wicket on the third morning at the P Saravanamuttu stadium.
Bangladesh, shot out for 62 in the first innings and trailing by 389 runs, went to lunch on the third day at 174-5 in their second knock.
Ashraful, who fell cheaply in three previous innings of the series, was unbeaten on 50 at the break. He has so far hit seven boundaries in his eighth Test half-century.
Rahim, called on to replace long-serving wicket-keeper Khaled Mashud for this match because of his batting ability, justified his selection with 47 not out containing six fours and a six.
It was the first time in the series that Bangladesh's batting flourished, but they still need 215 runs with five wickets in hand to make the hosts bat a second time.
Sri Lanka won last week's first Test at the Sinhalese Sports Club by an innings and 234 runs to take the lead in the three-match series.
Former captain Habibul Bashar made a positive start for Bangladesh by punching Dilhara Fernando through the covers off the back foot and then hooking the same bowler for another boundary.
Bangladesh added nine runs to their overnight score of 69-4 when Fernando gained revenge by shattering Bashar's stumps.
Ashraful brought up the half-century partnership by driving Lasith Malinga through the covers for his fifth boundary.
At the other end, Rahim hit two fours off Chaminda Vaas and then stepped out to loft Muttiah Muralitharan for an audacious six over the long-on fence.
Brief Scores (at lunch, D-3):
Bangladesh 62 and 174 for 5 (Ashraful 50 n o, Rahim 47 n o, Javed Omar 28; Fernando 3 for 48, Vaas 2 for 26) Vs Srilanka 451 for 6 decl (Sangakkara 200 n o, Warnapura 82).