The volenti non fit injuria maxim (who consents is not wronged) is quite distinct from the harm principle. First, it is a principle of law rather than morality, and second, if we were to search for the underlying moral foundation we are more likely to find it in deontology of individual rights and duties than in utilitarianism, with which the harm principle is traditionally associated (it goes back to Mill). Finally, even the volenti maxim does not assert the converse, that without consent a wrong is necessarily done, or that self-defense is the only exception to that. However, deontology generally allows violation of rights in only very narrow sets of circumstances.
In the trolley problem, utilitarianism, at least on its plain reading, favors sacrificing the few to save the many, and the scenario is often used as a strike against it because many people's moral intuitions rebel against such a judgment. In line with his utilitarianism, Mill's own formulation of the harm principle carves a very broad "exception" to violating one's rights without any consent, "the only purpose for which power can rightfully be exercised over any member of a civilised community against his will is to prevent harm to others." It is to be expected, in utilitarianism the utility, "common good" or some such, simply trumps individual rights every time. They may be assigned their own utilities and factored into the equation, but also can be overridden by many other considerations that contribute to the same utility. Absent other information, the rights of those sacrificed do not outweigh the lives of those saved, so Mill's harm principle advises shifting the trolley just as it advises inflicting harm in self-defense (although even Mill does not say that power should be exercised to prevent harm to others, only that it can be).
In deontology, on the other hand, self-defense and the trolley scenario are quite distinct morally, as those harmed have done nothing to deserve the rough treatment in the latter, but not in the former. Something like the "rights forfeiture" doctrine can, perhaps, be used to justify self-defense (although it is rather controversial), but not unleashing the trolley. Shaber even argues in The Volenti Maxim that "in some cases the consenter is wronged even if his consent is valid. Valid consent can only release others from consent-sensitive duties, not from consent-insensitive duties." In other words, some rights cannot be forfeited even consensually.