The survival of many microorganisms, like Leptospira or Spiroplasma bacteria, can depend on their ability to navigate towards regions of favorable viscosity. While this ability, called viscotaxis, has been observed in several bacterial experiments, the underlying mechanism remains unclear. We provide a framework to study viscotaxis of biological or synthetic self-propelled swimmers in slowly varying viscosity fields and show that suitable body shapes create viscotaxis based on a systematic asymmetry of viscous forces acting on a microswimmer. Our results shed new light on viscotaxis in Spiroplasma and Leptospira and suggest that dynamic body shape changes exhibited by both types of microorganisms may have an unrecognized functionality: to prevent them from drifting to low viscosity regions where they swim poorly. The present theory classifies microswimmers regarding their ability to show viscotaxis and can be used to design synthetic viscotactic swimmers, e.g., for delivering drugs to a target region distinguished by viscosity.