Zhangjiakou was a major battleground during Han–Xiongnu War. In 127 BC, Xiongnu cavalry attacked Shanggu (currently Huailai), Yuyang. The Emperor Wu of Han launched a successful counterattack. In 124 BC, Xiongnu cavalry invaded Dai Commandery. Emperor Wu ordered Wei Qing commanding 100,000 troops to counterattack. Wei Qing left the Great Wall more than 600 to 700 kilometers, encircled Xiongnu's head, Youxianwang (). In 122 BC, 50,000 Xiongnu invaded Shanggu, killed hundreds of people. In next March, Huo Qubing commanded 10,000 cavalry to counterattack and achieved success. In 119 BC, Wei Qing and Huo Qubing each commanded 50,000 cavalry. Huo Qubing departed from Dai Commandery, marched 2000 li northward crossing Gobi desert. Finally, Han troops defeated Xiongnu under Yizhixie completely. Following the success, a new office, the Colonel-Protector of the Wuhuan (), was established in Shanggu in order to prevent contact between the Wuhuan with the Xiongnu and to use them to monitor the Xiongnu activities. In 106 BC, Emperor Wu of Han organized the Western Han Dynasty into 13 province-sized prefectures, each administered by a cishi () or inspector, thus putting Shanggu and Dai under the jurisdiction of You Prefecture.