Our understanding of the link between neural activity and perception remains incomplete. Microstimulation and optogenetic experiments have shown that manipulating cortical activity can influence sensory-guided behaviour or elicit artificial percepts. And yet, some perceptual tasks can still be solved when sensory cortex is silenced or removed, suggesting that cortical activity may not always be essential. Reconciling these findings, and providing a quantitative framework linking cortical activity and behaviour, requires knowledge of the identity of the cells being activated during the behaviour, the engagement of the local and downstream networks, and the cortical and behavioural state. Here, we performed two-photon population calcium imaging in L2/3 primary visual cortex (V1) of headfixed mice performing a visual detection task while simultaneously activating specific groups of neurons using targeted two-photon optogenetics during low contrast visual stimulation. Only activation of groups of cells with similar tuning to the relevant visual stimulus led to a measurable bias of detection behaviour. Targeted photostimulation revealed signatures of centre-surround, predominantly inhibitory and like-to-like connectivity motifs in the local network which shaped the visual stimulus representation and partially explained the change in stimulus detectability. Moreover, the behavioural effects depended on overall performance: when the task was challenging for the mouse, V1 activity was more closely linked to performance, and cortical stimulation boosted perception. In contrast, when the task was easy, V1 activity was less informative about performance and cortical stimulation suppressed stimulus detection. Altogether, we find that both the selective routing of information through functionally specific circuits, and the prevailing cortical state, make similarly large contributions to explaining the behavioural response to photostimulation. Our results thus help to reconcile contradictory findings about the involvement of primary sensory cortex in behavioural tasks, suggesting that the influence of cortical activity on behaviour is dynamically reassigned depending on the demands of the task.