This is a great question and
@Ceke2002 and
@Guero's responses are totally on point! One other thing to consider, if you're in a position to do so, is advocating for intake forms that ask about patients' assigned sex at birth and gender identity, and give space to list a preferred name and pronouns. It signals to trans patients that this is a respectful and trans-savvy environment, takes some of the onus off of providers to figure out when and how to ask about those things, and heads off some awkward mistakes. Institutional inclusion ftw.
I'd also add that many trans folks going into a healthcare encounter will have thought carefully about whether and how to come out to the doctor and other staff. I'd wager (no data here) that we are generally pretty good about disclosing proactively when we know that it's relevant, and can say for sure that many of us choose not to disclose if we think it's not necessary. For example, establishing care with a new PCP = probably... popping into urgent care with nausea and vomiting = quite possibly not. Not saying that this is ideal from a medical perspective, but it's a strategy for self-protection after past experiences of discrimination in healthcare.
So, the best way to ask will be mindful of that context: ask in a way that's open-ended and non-judgmental, at a logical point in the encounter (toward the beginning if you're asking about preferred name and pronouns; if you're asking more detailed questions about transition-related medical history, maybe further in once you've had a chance to establish some rapport). Normalize by emphasizing that this is something you discuss with every patient to make sure that you're providing the most comprehensive and respectful care. And if you ask for further details, stick to questions that are truly necessary for their care, and explain how they're relevant. (If a trans man shows up to urgent care with a sinus infection, no need to ask whether he's thinking about a hysterectomy any time soon, etc.)