Listen to this article
Dalla Porta was leading in the early stages when his Leopard Honda bike suffered an engine failure, with Tony Arbolino (VNE Snipers) later also retiring from the lead with an apparent mechanical problem.
Bester Capital Dubai rider Masia meanwhile crashed at Turn 1 while being squeezed by Darryn Binder (CIP), the Spaniard retiring for the third time this season.
Binder later also retired from podium contention, having been taken out by pole-sitter Gabriel Rodrigo (Gresini) at Turn 10 on the penultimate lap.
That incident was followed by Honda Team Asia's Kaito Toba leading into the final lap, with Aron Canet and Alonso Lopez battling behind him.
Toba held the lead after the main straight but the two local riders were all over him at Turn 10 and Toba cracked under the pressure, sliding off track.
In the mayhem, Ramirez moved ahead of both Canet and Lopez, and he completed the remaining four corners of the race to score his first win of the season.
Canet finished second as Sky VR46 rookie Celestino Vietti picked off Lopez at the final turn to snatch the final podium position.
Vietti's teammate Dennis Foggia was fifth ahead of front row starter Ai Ogura (Honda Team Asia) with Romano Fenati (VNE Snipers) taking his best finish since his Moto3 return in seventh.
The top 10 was completed by Ayumu Sasaki (Petronas Sprinta), EG0,0 wildcard Ryusei Yamanaka and Pruestl's Jakub Kornfeil.
Title contender Niccolo Antonelli fell out of podium contention after running wide at Turn 1, the Italian settling for 11th, while John McPhee miraculously avoided a highside at Turn 10 of the final lap. While he managed to hang on to his bike, he dropped from the lead pack to 13th.
The race also saw a dramatic multi-bike crash caused by Can Oncu losing control of his bike at Turn 4.
He first wiped out Albert Arenas and then collected other riders, with Sergio Garcia, Raul Fernandez, Vicente Perez and Filip Salac all hitting the deck simultaneously.
Tatsuki Suzuki fell on the opening lap at Turn 10 with Andrea Migno and Makar Yurchenko also having incidents during the race.
With his second-place finish, Canet's lead is up to 23 points over Dalla Porta in the championship.
|3||Celestino Vietti Ramus||KTM||21||0.146|
|Kaito Toba||Honda||20||1 Lap|
|Gabriel Rodrigo||Honda||19||2 Laps|
|Makar Yurchenko||KTM||18||3 Laps|
|Jaume Masia||KTM||13||8 Laps|
|Tony Arbolino||Honda||12||9 Laps|
|Filip Salač||KTM||9||12 Laps|
|Andrea Migno||KTM||5||16 Laps|
|Can Öncü||KTM||5||16 Laps|
|Raúl Fernández||KTM||4||17 Laps|
|Sergio García||Honda||4||17 Laps|
|Albert Arenas||KTM||4||17 Laps|
|Lorenzo Dalla Porta||Honda||3||18 Laps|
|View full results|
Mugello Moto3: Arbolino edges Dalla Porta for maiden win
Assen Moto3: Arbolino scores win with last-lap move