No. No, no, no, no, no. Put the pen down and back away from the keyboard. If this ending appeals to you then you’re a menace to society and should not be allowed out in public. Hallucinations are acceptable because they’re temporary and indicative of something actually going on. ‘Then I woke and it was all a dream’ as an ending is not. The reader shouldn’t be asked to invest time and emotion in a story, only to be told at the end that it never actually happened. They lose all sense of engagement in the characters, closure in the story and trust in the writer.
Playing with this trope in order to subvert it is fine. Nightmare on Elm Street ends with making you think it’s all a dream before the main nightmare character turns up in real life, giving the audience a final shock and question as the finale. The subversion in The Matrix works because it’s done early and is a major world-building aspect. Chronicles of Thomas Covenant have the main character believing he’s in a dream and acting accordingly, then coming to doubt it. Contrast these with things like Mirrormask and the film of Breaking Dawn – the sense of frustration and disillusion (although at least Mirrormask is pretty to watch). To quote Terry Pratchett’s Wee Free Men:
Tiffany sighed. “And then she woke up and it was all a dream.” It was the worst ending you could have to any story.
The trouble is, it’s used so extensively and in some fairly revered pieces of storytelling, The Wizard of Oz being a prime example. The point is that this doesn’t invalidate the main bulk of the story or the quality of the writing. It invalidates the story as a whole. Tolkien likened it to ‘a good picture in a disfiguring frame’. If you’ve absolutely got to use it, make sure it’s obviously a dream, brief, and not the end. Even subversion isn’t necessarily enough here, since ‘dream’ subversions have also been pretty extensively explored. There’s a nicely written article here documenting the history of film ending twists which demonstrates the dangers of trying to one-up subversions.
I’d expect some people to disagree with me, citing their favourite films/books/episodes/whatever as evidence that it can work. That’s fine – of course you’re entitled to have your own opinions. Mine is that it’s a horribly lazy ending designed to piss off your audience. There are exceptions but a) they are exceptions, and b) they almost always get by on the quality of the rest of the story. They make it despite the handicap. Once again, quality is what counts.